依赖管理
问题
SPM、CocoaPods、Carthage 如何选择?
答案
三大依赖管理对比
| SPM | CocoaPods | Carthage | |
|---|---|---|---|
| 维护方 | Apple 官方 | 社区 | 社区 |
| 配置文件 | Package.swift | Podfile | Cartfile |
| 集成方式 | Xcode 原生 | 修改 xcworkspace | 手动添加 framework |
| 编译 | 源码编译 | 源码编译 | 预编译 framework |
| 二进制缓存 | ✅(Xcode 15+) | ❌ | ✅ |
| 生态 | 快速增长 | 最丰富 | 少 |
SPM 使用
// Package.swift
let package = Package(
name: "MyLibrary",
platforms: [.iOS(.v15)],
products: [
.library(name: "MyLibrary", targets: ["MyLibrary"]),
],
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.0.0"),
],
targets: [
.target(name: "MyLibrary", dependencies: ["Alamofire"]),
.testTarget(name: "MyLibraryTests", dependencies: ["MyLibrary"]),
]
)
Xcode 中:File → Add Package Dependencies → 输入仓库 URL。
2024+ 推荐
新项目优先使用 SPM。Apple 官方维护、Xcode 原生集成、无需额外工具。只有极少数老库不支持 SPM 时才考虑 CocoaPods。
常见面试问题
Q1: CocoaPods 的原理?
答案:pod install 会生成一个 xcworkspace,包含原项目和 Pods 项目。Pods 项目把所有依赖编译成静态库/动态库,通过 xcconfig 设置 Header Search Paths 和链接选项。
Q2: SPM 的 resolved 文件要提交到 Git 吗?
答案:Package.resolved 类似 Podfile.lock,记录精确版本。应该提交到 Git,保证团队成员使用相同版本。