IntermediateLesson 12 of 16
Swift Package Manager & Tests – Swift
Structuring projects, adding dependencies, and testing code.
A Swift package consists of a Package.swift (written in Swift!) and a Sources folder. Targets are executables or libraries; dependencies are entered as a URL plus a version rule.
// Package.swift
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "Hallo",
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.3.0")
],
targets: [
.executableTarget(
name: "Hallo",
dependencies: [.product(name: "ArgumentParser", package: "swift-argument-parser")]
),
.testTarget(name: "HalloTests", dependencies: ["Hallo"])
]
)swift package init --type executable # new project
swift build # build
swift run # run
swift test # run tests
swift package update # update dependenciesYou control visibility with access levels: private, fileprivate, internal (default, visible in the whole module), public, and open (for libraries, also overridable outside). Only public elements are visible to another package.
public struct Rechner {
public init() {}
public func addiere(_ a: Int, _ b: Int) -> Int { a + b }
private func intern() {} // visible only in this type
}Tests: the modern Swift Testing (from Swift 6 / Xcode 16) uses @Test and #expect; the classic XCTest uses classes with test... methods. Both run with swift test.
import Testing
@testable import Hallo
@Test func addiertZweiZahlen() {
#expect(Rechner().addiere(2, 3) == 5)
}
@Test(arguments: [1, 2, 3])
func istPositiv(_ n: Int) {
#expect(n > 0)
}import XCTest
@testable import Hallo
final class RechnerTests: XCTestCase {
func testAddiere() {
XCTAssertEqual(Rechner().addiere(2, 3), 5)
}
func testFehler() throws {
XCTAssertThrowsError(try abheben(saldo: 0, betrag: 1))
}
}TipIn Xcode projects you manage packages via *File > Add Package Dependencies*. Tests run there with Cmd+U, and individual test methods via the diamond next to them.
WarningWithout
public, a type from another module is not reachable, which is the most common mistake when moving code into its own package. @testable import grants tests access to internal.