Swift Package Management
Introduction
Swift Package Manager (SPM) is the official tool for managing dependencies in Swift projects. This guide covers package creation, dependency management, and best practices.
Creating a Package
Basic Structure
// Package.swift
// swift-tools-version:5.7
import PackageDescription
let package = Package(
name: "MyLibrary",
platforms: [.iOS(.v15), .macOS(.v12)],
products: [
.library(
name: "MyLibrary",
targets: ["MyLibrary"])
],
dependencies: [
.package(url: "https://github.com/example/package.git", from: "1.0.0")
],
targets: [
.target(
name: "MyLibrary",
dependencies: []),
.testTarget(
name: "MyLibraryTests",
dependencies: ["MyLibrary"])
]
)
Managing Dependencies
Adding Dependencies
dependencies: [
.package(url: "https://github.com/example/package.git", from: "1.0.0"),
.package(url: "https://github.com/another/lib.git", .branch("main")),
.package(url: "https://github.com/third/pkg.git", .exact("2.0.0"))
]
Version Requirements
.from("1.0.0"): Version 1.0.0 or higher.upToNextMajor(from: "1.0.0"): Range 1.0.0..<2.0.0.upToNextMinor(from: "1.1.0"): Range 1.1.0..<1.2.0.exact("1.0.0"): Exactly version 1.0.0
Package Organization
Directory Structure
MyLibrary/
├── Package.swift
├── README.md
├── Sources/
│ └── MyLibrary/
│ ├── MyLibrary.swift
│ └── Additional.swift
└── Tests/
└── MyLibraryTests/
└── MyLibraryTests.swift
Command Line Interface
Common Commands
# Initialize a new package
swift package init
# Build the package
swift build
# Run tests
swift test
# Update dependencies
swift package update
# Generate Xcode project
swift package generate-xcodeproj
Best Practices
- Version your packages semantically
- Document dependencies clearly
- Keep packages focused and modular
- Write comprehensive tests
- Maintain backward compatibility
Integration with Xcode
Adding Package Dependencies
- File > Add Packages
- Enter package URL
- Choose version requirements
- Select target to add dependency
Publishing Packages
Requirements
- Public repository
- Semantic versioning
- Documentation
- License
- README file
Next Steps
- Study Performance Optimization
- Explore Security
- Review Testing and Debugging