1

我目前正在开发一个 Swift 包,我想在其中使用其他 Swift 包。为此,我将要使用的包添加到 Package.swift 中的依赖项中

dependencies: [
    // Dependencies declare other packages that this package depends on.
    // .package(url: /* package url */, from: "1.0.0"),
    .package(url: "https://github.com/jedisct1/swift-sodium.git", .upToNextMajor(from: "0.9.1")),
    .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.5.0"))
],

这是我完整的 Package.swift:

// swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "SpaceCryptography",
    platforms: [
        .iOS(.v10),
        .watchOS(.v3)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "SpaceCryptography",
            targets: ["SpaceCryptography"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
        .package(url: "https://github.com/jedisct1/swift-sodium.git", .upToNextMajor(from: "0.9.1")),
        .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.5.0"))
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "SpaceCryptography",
            dependencies: []),
        .testTarget(
            name: "SpaceCryptographyTests",
            dependencies: ["SpaceCryptography"]),
    ]
)

然后,这些包出现在项目导航器中的“包依赖项”下。但是当我尝试使用“import Alamofire”时,我收到一条错误消息,提示“没有这样的模块‘Alamofire’。如何在我自己的包中正确使用这些包?

4

2 回答 2

2

您需要将它们添加到目标的依赖项部分。像这样 :

targets: [
    // Targets are the basic building blocks of a package. A target can define a module or a test suite.
    // Targets can depend on other targets in this package, and on products in packages this package depends on.
    .target(
        name: "SpaceCryptography",
        dependencies: ["Alamofire"]),
    .testTarget(
        name: "SpaceCryptographyTests",
        dependencies: ["SpaceCryptography", "Alamofire"]),
]
于 2022-02-04T10:16:18.650 回答
1

如前所述,您必须将依赖项“Alamofire”和“Sodium”设置为目标。例如:

.target(
   name: "SpaceCryptography",
   dependencies: ["Alamofire", "Sodium"]),

我建议也给上面定义的依赖包命名:

dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
        .package(name: "Sodium", url: "https://github.com/jedisct1/swift-sodium.git", .upToNextMajor(from: "0.9.1")),
        .package(name: "Alamofire" url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.5.0"))
    ]
于 2022-02-04T10:20:28.187 回答