Getting Started with Swift Package Manager
Swift Package Manager (SPM) is the official package manager for Swift. Let’s learn how to use it effectively.
What is SPM?
SPM is a tool for managing the distribution of Swift code. It’s integrated directly into Swift build system.
Package.swift Structure
// swift-tools-version:5.9
import PackageDescription
let package = Package(
name: "MyLibrary",
platforms: [
.iOS(.v15),
.macOS(.v12)
],
products: [
.library(
name: "MyLibrary",
targets: ["MyLibrary"]
)
],
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire", from: "5.8.0")
],
targets: [
.target(
name: "MyLibrary",
dependencies: ["Alamofire"]
)
]
)
Adding Dependencies
Via Xcode
- File → Add Package Dependencies
- Enter repository URL
- Select version rules
- Choose products to add
Via Package.swift
dependencies: [
.package(url: "https://github.com/SnapKit/SnapKit", from: "5.6.0"),
.package(url: "https://github.com/onevcat/Kingfisher", from: "7.10.0")
]
Using Packages
import Kingfisher
import SnapKit
class MyViewController: UIViewController {
private let imageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadImage()
}
private func setupUI() {
view.addSubview(imageView)
imageView.snp.makeConstraints { make in
make.center.equalToSuperview()
make.size.equalTo(200)
}
}
private func loadImage() {
imageView.kf.setImage(with: URL(string: "https://example.com/image.jpg"))
}
}
Local Packages
dependencies: [
.package(path: "../MyLocalPackage")
]
Version Rules
| Rule | Example | Meaning |
|---|---|---|
from |
from: "1.0.0" |
≥ 1.0.0 |
upToNextMajor |
"1.0.0"..<"2.0.0" |
≥ 1.0.0, < 2.0.0 |
upToNextMinor |
"1.0.0"..<"1.1.0" |
≥ 1.0.0, < 1.1.0 |
exact |
"1.0.0" |
Exactly 1.0.0 |
SPM makes dependency management clean and simple.