Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 146 ยท Advanced Swift

Swift Package Manager

Learn how Swift Package Manager works: Package.swift, targets, products, dependencies and version rules, tests and commands, with runnable models of its core ideas.

Every real Swift project is more than one file. You split code into modules, reuse libraries written by other people, run tests and build for several platforms. The tool that organizes all of this is the Swift Package Manager, usually called SwiftPM. It ships with every Swift toolchain, it is the build system behind the swift build, swift run and swift test commands, and Xcode uses it for dependencies too.

A package is just a folder with a file called Package.swift and some source files. The manifest is itself a Swift program: it builds a description of your package (its name, targets, dependencies) that SwiftPM reads. In this lesson you will learn the vocabulary, how version requirements work, how to read a manifest, and which commands you will use every day.

SwiftPM is a build tool, and the site's runner compiles a single `main.swift` file with `swiftc` directly: there is no `swift build`, no network and no package downloads here. So the manifests, folder trees and commands in this lesson are read-only examples. To make the ideas concrete, the runnable examples below are small models of what SwiftPM does (parsing versions, ordering a dependency graph), written in plain Swift. They are explanations, not SwiftPM itself.

The vocabulary

  • Package: a folder with a Package.swift manifest. It is the unit you version and share.
  • Module: a unit of compilation with its own namespace. When you write import Foundation you import the module Foundation.
  • Target: what the package builds. A target becomes one module. It is a library target (code for others), an executable target (a program), a test target, a macro or a plugin.
  • Product: what the package offers to the outside world: a library (other packages can depend on it) or an executable (an end user can run it). Targets that are not exposed through a product are internal to the package.
  • Dependency: another package you use, identified by a Git URL (or a local path) and a version requirement.

The default layout is a convention, so most manifests need no paths at all:

TEXT
Greeter/                      read-only example
โ”œโ”€โ”€ Package.swift
โ”œโ”€โ”€ Sources/
โ”‚   โ”œโ”€โ”€ GreeterKit/           library target  -> module GreeterKit
โ”‚   โ”‚   โ””โ”€โ”€ Greeting.swift
โ”‚   โ””โ”€โ”€ greeter/              executable target
โ”‚       โ””โ”€โ”€ main.swift
โ””โ”€โ”€ Tests/
    โ””โ”€โ”€ GreeterKitTests/      test target
        โ””โ”€โ”€ GreetingTests.swift

Reading a manifest

Here is a complete manifest for that package. It is read-only, because it needs SwiftPM and a network connection to download swift-argument-parser:

Swift
// swift-tools-version: 6.2
// Package.swift (read-only example)
import PackageDescription

let package = Package(
    name: "Greeter",
    platforms: [.macOS(.v14), .iOS(.v17)],
    products: [
        .library(name: "GreeterKit", targets: ["GreeterKit"]),
        .executable(name: "greeter", targets: ["greeter"]),
    ],
    dependencies: [
        .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
    ],
    targets: [
        .target(name: "GreeterKit"),
        .executableTarget(
            name: "greeter",
            dependencies: [
                "GreeterKit",
                .product(name: "ArgumentParser", package: "swift-argument-parser"),
            ]
        ),
        .testTarget(name: "GreeterKitTests", dependencies: ["GreeterKit"]),
    ]
)

Go through it line by line:

  • The first line, // swift-tools-version: 6.2, is not an ordinary comment. It tells SwiftPM which version of the manifest API to use and the minimum toolchain needed. Newer tools versions unlock newer manifest features, and, from 6.0 on, they select the Swift 6 language mode for your targets by default.
  • platforms sets the minimum OS versions on Apple platforms. Linux and Windows have no such setting.
  • products lists what you publish. GreeterKit is a library other packages can add. The executable is greeter.
  • dependencies declares packages, targets declares how they are used. The two-step design means that adding a package to the list does not make it available to code until a target names one of its products.
  • Targets name each other by string. GreeterKit is a target in this package, so a string is enough; ArgumentParser is a product of an external package, so you write .product(name:package:).

Why the manifest is Swift

Because Package.swift is an ordinary Swift program, you can use variables, conditions and loops in it. But what it does is just build a value: Package(...) is an initializer call, and SwiftPM reads the resulting value. The next example is a simplified stand-in with the same shape, with types we define ourselves, to show that a manifest is plain data:

Swift A manifest is just a value (stand-in types)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Keep manifests simple. They run in a sandbox at every resolve, and a clever manifest is hard for others (and for tools) to read.

Versions and requirements

SwiftPM dependencies use semantic versioning: major.minor.patch. By convention, an increase in patch fixes bugs, an increase in minor adds features without breaking anyone, and an increase in major may break your code. Requirements express how much change you accept:

Requirement Accepts Meaning
from: "1.5.0" 1.5.0 up to, but not including, 2.0.0 "At least this, same major version." The usual choice.
.upToNextMinor(from: "1.5.0") 1.5.0 up to, but not including, 1.6.0 Only bug fixes.
"1.2.0"..<"1.9.0" the range An explicit range.
exact: "1.5.2" only 1.5.2 Pinning; makes you responsible for every update.
branch: "main" / revision: "..." a Git branch or commit For unreleased work. Not allowed in published packages.

When you resolve, SwiftPM picks the highest version that satisfies every requirement in the whole dependency graph and records it in Package.resolved, so the next build (and your teammates' builds) get exactly the same versions until you run swift package update. This is how a model of it looks in code:

Swift Choosing a version from requirements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice the last line: when no published version satisfies the requirement, real SwiftPM stops with a resolution error and tells you which requirements conflict. A common cause is that two of your dependencies require incompatible versions of a third. This is why library authors should keep ranges wide (from:), and applications can pin tighter if they need to.

Targets depend on targets

Inside a package, targets form a graph. SwiftPM builds a target only after everything it depends on, and cycles are not allowed: if A imports B and B imports A, the compiler cannot decide which to build first. This model computes a valid build order the same way, with a depth-first search, and detects the cycle:

Swift Build order and cycle detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Real SwiftPM reports the same situation as error: cyclic dependency declaration found: A -> B -> C -> A. The fix is always to move the shared code into a third target that both depend on.

What happens when a package is not there

Your code can only import modules that the compiler can find. If a dependency is missing from the package (or you are in a single file like the runner here), you get a compile error:

Swift Importing a module that is not installed (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports error: no such module 'ArgumentParser'. In a real project that message has three common causes: the package is missing from dependencies, the target does not list the product in its own dependencies, or the package does not support the platform you are building for.

Everyday commands (read-only)

Terminal
# read-only example: run these in a terminal on your machine
swift package init --type library      # create a library package (also: executable, macro)
swift build                            # debug build into .build/
swift build -c release                 # optimized build
swift run greeter --name Sam           # build and run an executable target
swift test                             # build and run all test targets
swift test --filter GreetingTests      # run matching tests
swift package resolve                  # fetch dependencies as in Package.resolved
swift package update                   # move to the newest versions the requirements allow
swift package show-dependencies        # print the dependency tree
swift package clean                    # remove build artifacts

Add Package.resolved to version control for applications, so everyone builds with the same versions. Do not commit the .build/ directory. For a library, Package.resolved is optional, because the app that uses your library resolves its own graph.

More features worth knowing

  • Resources: resources: [.process("Assets")] bundles files, and Bundle.module finds them at run time.
  • Conditional dependencies: .product(name: "Crypto", package: "swift-crypto", condition: .when(platforms: [.linux])).
  • Swift settings per target: swiftSettings: [.enableUpcomingFeature("ExistentialAny")] turns on upcoming language features one by one (see language versions).
  • Plugins: build tool plugins generate code before compilation; command plugins add commands such as swift package generate-documentation for DocC (see documentation comments).
  • Macros: a macro is its own target type that SwiftPM builds as a compiler plugin (see macros overview).
  • Local dependencies: .package(path: "../MyLibrary") is perfect while two packages evolve together.
  • Binary targets: .binaryTarget links a prebuilt framework.

When you are unsure how to structure a project, create a package, even for a small command-line tool. You get tests, dependency management and a clean module layout for free, and later splitting a target in two is cheap.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the first line // swift-tools-version: 6.2 in Package.swift?

    It looks like a comment but SwiftPM reads it. It decides which manifest features exist and which language mode targets use by default.
  2. 2. What does .package(url: ..., from: "1.5.0") accept?

    from: means at least that version and the same major version. .upToNextMinor(from:) is the stricter option.
  3. 3. What is the difference between a target and a product?

    Targets are built from source folders. Products (libraries and executables) are the targets you choose to publish.
  4. 4. Why are cyclic dependencies between targets not allowed?

    Each module must be compiled after the modules it imports. A cycle has no first module. Extract the shared code into a third target.
  5. 5. What does the compile error no such module 'ArgumentParser' usually mean?

    A module can only be imported when the build can find it: the package must be in dependencies and the product must be listed in the target's dependencies.

Summary

  • A Swift package is a folder with Package.swift; the manifest is a Swift program that builds a Package value.
  • Targets compile into modules; products are what a package offers (libraries and executables); dependencies are other packages identified by URL and version rule.
  • Default layout: Sources/<Target>, Tests/<Target>Tests.
  • from: "1.5.0" means "1.5.0 up to the next major version"; SwiftPM resolves the highest satisfying version and records it in Package.resolved.
  • Target dependencies form a graph that must not contain cycles.
  • Everyday commands: swift build, swift run, swift test, swift package update.
  • Nothing here can run in the browser: use the examples as templates on your own machine.

Next: Swift on Apple Platforms