Swift Package Manager (SPM)
Swift Package Manager (SPM)
Create packages, declare dependencies, and build libraries and executables with Swift Package Manager.
Create a New Package
Swift Package Manager (SPM) is Swift's built-in dependency manager and build tool.
Syntax: swift package init --type executable, swift build, swift run.
Example
$ mkdir hello-pkg && cd hello-pkg
$ swift package init --type executable
$ swift build
$ swift run
Hello, world!
This example initializes an executable package, builds it, and runs the generated binary.
Package.swift
The manifest file Package.swift describes your package, products, and dependencies.
Syntax: declare products, add dependencies, and list targets that build your code.
Example
// swift-tools-version: 5.10
import PackageDescription
let package = Package(
name: "hello-pkg",
products: [
.executable(name: "hello-pkg", targets: ["hello-pkg"]),
],
dependencies: [
// .package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0")
],
targets: [
.executableTarget(
name: "hello-pkg",
dependencies: []
)
]
)
This basic manifest declares an executable product and a single target with no external dependencies.
Targets, Products, Dependencies
Targets build code.
Products are what you ship (executables or libraries).
Dependencies are other packages you use.
Syntax: add .package(url:..., from: ...) in dependencies, and reference it via .product(name:..., package:...) in target dependencies.
Example: Add swift-argument-parser
// swift-tools-version: 5.10
import PackageDescription
let package = Package(
name: "hello-pkg",
products: [
.executable(name: "hello-pkg", targets: ["hello-pkg"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.2.0")
],
targets: [
.executableTarget(
name: "hello-pkg",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser")
]
)
]
)
import ArgumentParser
@main
struct Hello: ParsableCommand {
@Option(name: .shortAndLong, help: "Name to greet")
var name: String = "Swift"
mutating func run() throws {
print("Hello, \(name)!")
}
}
$ swift build
$ swift run hello-pkg --name W3Schools
Hello, W3Schools!
This example adds a dependency and links its product into the executable target, then builds and runs with an option.
Add a Dependency
Add a dependency in dependencies and link it in your target.
Then run swift build.
Syntax: swift package resolve to update dependencies and swift package clean to clean build artifacts.
Tip: Use swift package resolve to update dependencies and swift package clean to clean build artifacts.