为类库添加Swift Package Manager支持 - ShenYj/ShenYj.github.io GitHub Wiki

支持 Swift Package Manager

PackageDescription API 官方文档

一、初始化SPM相关配置文件

  • 进入到.xcodeproj同级目录下

    swift package init --type library
    Creating library package: Example
    Creating Package.swift
    Creating README.md
    Creating .gitignore
    Creating Sources/
    Creating Sources/Example/Example.swift
    • 参数说明

      • --type
      • empty: 空包
        • Source 文件夹下什么都没有,也不能编译
      • library: 静态包
        • Source 文件夹下有个和包同名 swift 文件,里面有个空结构体
      • executable: 可执行包
        • Source 文件夹下有个 main.swift 文件,在 build 之后会在 .build/debug/ 目录下生成一个可执行文件,可通过 swift run 或者直接点击运行,从而启动一个进程
      • system-module: 系统包
        • 这种包是专门为了链接系统库(例如 libgitjpeglibmysql 这种系统库)准备的,本身不需要任何代码,所以也没有 Source 文件夹,但是需要编辑 module.modulemap 文件去查找系统库路径 (Swift 4.2 已经被其他方式取代)

Package.swift,这个文件就相当于 CocoaPodsPodfile 或者 CarthageCartfile.


二、类库配置

  • SBLibrary为例(SB是Swift Basic的缩写, 不要歪楼开脑洞😅)

    // swift-tools-version:5.3
    import PackageDescription
    
    let package = Package(
        name: "SBLibrary",
        platforms: [.iOS(.v10)],
        products: [
            // Products define the executables and libraries a package produces, and make them visible to other packages.
            .library(name: "SBLibrary", targets: ["SBLibrary"]),
    
            .library(name: "SBLibraryDynamic", type: .dynamic, targets: ["SBLibrary"]),
    
            .library(name: "SBLibraryStatic", type: .static, targets: ["SBLibrary"]),
        ],
        dependencies: [
            // Dependencies declare other packages that this package depends on.
            // .package(url: /* package url */, from: "1.0.0"),
            .package(url: "https://github.com/Quick/Quick.git", from: "2.2.0"),
            .package(url: "https://github.com/Quick/Nimble.git", from: "8.0.7")
        ],
        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: "SBLibrary",
                dependencies: []),
            .testTarget(
                name: "Pods-SBLibrary_Tests",
                dependencies: ["SBLibrary", "Quick", "Nimble"],
                path: "../SBLibrary/"),
        ]
    )
⚠️ **GitHub.com Fallback** ⚠️