Swift Package Manager: Package.swift
Swift Package Manager (SwiftPM) is Swift's build tool and package manager, part of the Swift toolchain. It plays two roles in iOS projects: Xcode uses it to fetch and build dependencies, and teams use it to split their own code into local packages with clear boundaries (the iOS counterpart of Gradle modules). Unlike Xcode, SwiftPM itself also runs on Linux and Windows, so a package without Apple-only frameworks can be built and tested anywhere Swift is installed.
Note: this course's container has no Swift toolchain, so SwiftPM commands are shown non-run with their typical output. They're the same on macOS and Linux.
The manifest
Package.swift is Swift code that builds a Package value. The first line is mandatory: it sets the tools version, i.e. which manifest API and language mode the package uses.
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "Core",
platforms: [.iOS(.v17), .macOS(.v14)], // minimum deployment targets
products: [
.library(name: "Core", targets: ["Core"]), // what other packages/apps can depend on
.executable(name: "core-tool", targets: ["CoreTool"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-collections.git", from: "1.1.0"),
.package(url: "https://github.com/apple/swift-argument-parser.git", .upToNextMinor(from: "1.5.0")),
.package(path: "../Analytics"), // a local package in the same repository
],
targets: [
.target(
name: "Core",
dependencies: [.product(name: "Collections", package: "swift-collections")],
resources: [.process("Resources")]
),
.executableTarget(
name: "CoreTool",
dependencies: ["Core", .product(name: "ArgumentParser", package: "swift-argument-parser")]
),
.testTarget(name: "CoreTests", dependencies: ["Core"]),
]
)| Concept | Meaning | Gradle analogy |
|---|---|---|
| Target | a module: sources in Sources/<Target>/ (tests in Tests/<Target>/) |
a source set / module |
| Product | what the package exports: .library or .executable built from targets |
a published artifact |
| Dependency | another package, by URL + version requirement, or by local path | a dependencies {} coordinate |
.product(name:package:) |
use one product of a dependency in a target | implementation(libs.x) |
platforms |
minimum OS versions | minSdk |
.binaryTarget |
a prebuilt .xcframework (local path or URL + checksum) |
a prebuilt AAR |
Targets can only import what they declare, so the manifest is the module graph: CoreTool can use Core and ArgumentParser, but Core can't accidentally import ArgumentParser.
The layout and the commands
Core/
├── Package.swift
├── Package.resolved exact versions + revisions (commit it for apps and tools)
├── Sources/
│ ├── Core/Greeter.swift
│ ├── Core/Resources/…
│ └── CoreTool/main.swift
└── Tests/CoreTests/GreeterTests.swiftswift package init --type library --name Core # scaffold a package
swift build # debug build into .build/debug
swift build -c release # release build (-O) into .build/release
swift test # build and run the test targets
swift test --filter CoreTests.GreeterTests # one test class
swift run core-tool --help # build and run an executable product
swift package describe # the parsed manifest
swift package show-dependencies --format json # the resolved graphA typical first build looks like this (trimmed):
$ swift build
Fetching https://github.com/apple/swift-collections.git
Fetched https://github.com/apple/swift-collections.git from cache (1.12s)
Computing version for https://github.com/apple/swift-collections.git
Computed https://github.com/apple/swift-collections.git at 1.2.1 (1.50s)
Creating working copy for https://github.com/apple/swift-collections.git
Working copy of https://github.com/apple/swift-collections.git resolved at 1.2.1
Building for debugging...
[12/12] Linking core-tool
Build complete! (24.13s)Local packages inside an app
Most iOS apps of any size now keep their code in local packages and leave a thin app target on top:
Hello.xcworkspace
├── Hello.xcodeproj app target: App.swift, assets, Info.plist
└── Packages/
├── Core/Package.swift models, networking
├── Features/Package.swift screens, depends on Core
└── DesignSystem/Package.swiftThe benefits are the same as Gradle modules: enforced boundaries, parallel builds, and fast tests (swift test in Core/ on Linux CI, without a simulator, when the package doesn't import UIKit).
A runnable model of version requirements
SwiftPM requirements are ranges over semantic versions; the resolver picks the highest version that satisfies every requirement in the graph:
| Requirement | Allows | Typical use |
|---|---|---|
from: "1.1.0" (= .upToNextMajor(from:)) |
>= 1.1.0, < 2.0.0 |
the default |
.upToNextMinor(from: "1.5.0") |
>= 1.5.0, < 1.6.0 |
packages that break things in minors |
exact: "1.5.2" |
only 1.5.2 |
last resort; blocks other packages' updates |
"1.2.0"..<"1.4.0" |
the given range | |
branch: "main", revision: "…" |
a commit, no version semantics | development only |
def parse(v):
return tuple(int(x) for x in v.split("."))
def allows(req, v):
kind, base = req
b, x = parse(base), parse(v)
if kind == "from": # up to next major
return b <= x < (b[0] + 1, 0, 0)
if kind == "upToNextMinor":
return b <= x < (b[0], b[1] + 1, 0)
if kind == "exact":
return x == b
raise ValueError(kind)
tags = ["1.0.3", "1.1.0", "1.1.4", "1.2.1", "1.5.0", "1.5.2", "1.6.0", "2.0.0"]
def resolve(requirements):
ok = [t for t in tags if all(allows(r, t) for r in requirements)]
return max(ok, key=parse) if ok else "no solution"
print("app: from 1.1.0 ->", resolve([("from", "1.1.0")]))
print("app: upToNextMinor 1.5.0 ->", resolve([("upToNextMinor", "1.5.0")]))
print("app from 1.1.0 + lib upToNextMinor 1.1.0 ->", resolve([("from", "1.1.0"), ("upToNextMinor", "1.1.0")]))
print("app exact 1.5.2 + lib from 1.6.0 ->", resolve([("exact", "1.5.2"), ("from", "1.6.0")]))app: from 1.1.0 -> 1.6.0
app: upToNextMinor 1.5.0 -> 1.5.2
app from 1.1.0 + lib upToNextMinor 1.1.0 -> 1.1.4
app exact 1.5.2 + lib from 1.6.0 -> no solution
2.0.0 is never chosen by from: "1.1.0": a new major is a breaking change by semver's rules, so upgrading across majors is always an explicit edit. And one exact: pin anywhere in the graph can make it unsolvable, which SwiftPM reports as a dependency conflict naming both requirements.
Test yourself
What does .package(url: …, from: "1.1.0") allow?
- Only 1.1.0
- Any version >= 1.1.0 and < 2.0.0
- Any version >= 1.1.0, including 2.x
- >= 1.1.0 and < 1.2.0
In Package.swift, what is a product?
- A Swift source file
- What the package exports for others to depend on: a library or an executable built from targets
- The resolved file
- A test bundle
Why can parts of an iOS codebase be tested on Linux CI with SwiftPM?
- Linux has a simulator
- SwiftPM and the Swift toolchain run on Linux, so packages that don't import Apple-only frameworks build and test there
- Xcode runs on Linux
- They can't