跳到主要内容

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​

  1. Version your packages semantically
  2. Document dependencies clearly
  3. Keep packages focused and modular
  4. Write comprehensive tests
  5. Maintain backward compatibility

Integration with Xcode​

Adding Package Dependencies​

  1. File > Add Packages
  2. Enter package URL
  3. Choose version requirements
  4. Select target to add dependency

Publishing Packages​

Requirements​

  1. Public repository
  2. Semantic versioning
  3. Documentation
  4. License
  5. README file

Next Steps​

  1. Study Performance Optimization
  2. Explore Security
  3. Review Testing and Debugging