Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

Building a Swift package

From one file to a project: packages, targets, and products; modules and access control; a command-line program; tests with swift test; dependencies and versions; and where to go after this tutorial.

CS61A
Applications · Conclusion
Swift book
Access Control

Every program so far has been one file, run with swift file.swift. That works for a lab, but not for anything bigger. Real programs are split into parts with clear boundaries, come with their tests, use code other people wrote, and can be used by other people in turn. In Swift, the unit for all of this is a package.

This lesson turns Lesson 20’s calculator into a package with three parts: a library that other code can use, a command-line program built on the library, and a test suite. The lab walks you through building it yourself.

Packages, targets, and products

A package is a folder with a manifest file, Package.swift, at the top. The Swift Package Manager, which comes with Swift, reads the manifest and knows how to build, run, and test everything in the folder.

mkdir Calculator
cd Calculator
swift package init --type library

This creates a manifest, a source folder, and a test folder. After the changes in this lesson, the package looks like this:

Calculator/
├── Package.swift
├── Sources/
│   ├── Calculator/
│   │   └── Calculator.swift     the library
│   └── calc/
│       └── main.swift           the command-line program
└── Tests/
    └── CalculatorTests/
        └── CalculatorTests.swift

And this is the manifest that describes it. It is ordinary Swift code:

// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "Calculator",
    products: [
        .library(name: "Calculator", targets: ["Calculator"]),
        .executable(name: "calc", targets: ["calc"]),
    ],
    targets: [
        .target(name: "Calculator"),
        .executableTarget(name: "calc", dependencies: ["Calculator"]),
        .testTarget(name: "CalculatorTests", dependencies: ["Calculator"]),
    ]
)

The vocabulary:

  • A target is a group of source files built together, in the folder of the same name under Sources or Tests. Each target becomes a module. Here there are three: the library, the program, and the tests.
  • Dependencies between targets say which modules can use which. The program and the tests both depend on the library; the library depends on nothing.
  • A product is what the package offers to the outside world: a library that other packages can use, or an executable that people can run.
  • The comment on the first line is not decoration. swift-tools-version says which version of the package manager the manifest needs, and it also selects the Swift 6 language mode, with the data-race checking from Lesson 22.

Modules and access control

A module is a boundary. Inside one, every declaration can see every other. Across one, a declaration is visible only if it says so. This is Lesson 6’s abstraction barrier, enforced by the compiler: the library decides what its users may depend on, and can change everything else freely.

Swift has six levels of access, from most open to most closed:

Level Visible to
open other modules, which may also subclass and override it
public other modules
package other modules in the same package
internal its own module (the default)
fileprivate its own source file
private the enclosing declaration, and its extensions in the same file

Since internal is the default, everything in a one-file program was visible everywhere, and access control never came up. In the library, the tokenizer, parser, and evaluator stay internal, and only the entry points become public:

/// An error in a Calculator program, with a message for the user.
public struct CalcError: Error, Equatable {
    public let message: String

    init(_ message: String) {
        self.message = message
    }
}

// Token, Expr, tokenize, parse, evaluate, and apply are Lesson 20's code,
// unchanged except that they throw CalcError with typed throws. None of them
// is public.

/// Evaluates one Calculator expression, such as `(+ 1 (* 2 3))`.
public func calculate(_ text: String) throws(CalcError) -> Int {
    try evaluate(parse(tokenize(text)))
}

/// Evaluates an expression and describes the result or the error.
public func run(_ text: String) -> String {
    do {
        return String(try calculate(text))
    } catch {
        return "Error: \(error.message)"
    }
}

Notice the details:

  • A public type does not make its members public. message needs its own public, and the initializer stays internal, so other modules can read errors but only the library can create them.
  • Comments that start with /// are documentation comments. Xcode and other editors show them when you use the function, and Swift’s DocC tool builds documentation websites from them.
  • If calc tried to call tokenize, the build would fail with “cannot find ‘tokenize’ in scope”. The internal parts are invisible, which means they can be rewritten without breaking any code outside the library.

Access control works inside a single file too, where private hides a property from everything except its own type:

What would Swift print?

struct Safe {
    private var code = 1234

    func check(_ guess: Int) -> Bool {
        guess == code
    }
}

extension Safe {
    var hint: Int { code % 10 }
}

let safe = Safe()
print(safe.check(1234), safe.hint)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answertrue 4

The extension can use code because it is in the same file as the type: extensions count as part of the declaration for private. Code outside the type, like the last line, can only use check and hint. Writing print(safe.code) there would not compile.

private(set), which appeared in Lessons 14 and 22, is access control too: the property can be read wherever the type is visible, but set only inside it.

A command-line program

An executable target runs the code at the top level of its main.swift, like a script. CommandLine.arguments holds the words typed after the program’s name (the first element is the name itself), and readLine() reads standard input:

import Calculator

let arguments = CommandLine.arguments.dropFirst()
if arguments.isEmpty {
    while let line = readLine() {   // a REPL, as in Lesson 20
        print(run(line))
    }
} else {
    print(run(arguments.joined(separator: " ")))
}

import Calculator brings in the library module, and with it only its public declarations. Build and run from the package folder:

swift build
swift run calc "(* 6 7)"
echo "(+ 1 2)" | swift run calc

The first prints 42, and the second sends a line through standard input to the REPL, which prints 3. swift build puts the finished program in .build/debug/calc; swift build -c release builds an optimized one in .build/release, which is the version to use for timing anything.

Tests in a package

The test target holds Lesson 23’s Swift Testing tests. @testable import lets tests see the library’s internal declarations too, so the tokenizer can be tested directly even though users of the library cannot call it:

import Testing
@testable import Calculator

@Test func addition() {
    #expect(run("(+ 1 2)") == "3")
}

@Test func divisionByZeroIsAnError() {
    #expect(throws: CalcError("division by zero")) {
        try calculate("(/ 1 0)")
    }
}

@Test(arguments: [("(- 5)", "-5"), ("(* 2 3 4)", "24"), ("(+)", "0"), ("(+ 1", "Error: missing )")])
func examples(input: String, expected: String) {
    #expect(run(input) == expected)
}

@Test func tokensForNestedCalls() {
    #expect(tokenize("(+ 1 (* 2 3))").count == 9)
}
swift test

swift test builds everything and runs every test, reporting each one and each argument of examples separately. Because CalcError is Equatable, #expect(throws:) can check for one exact error, not just any error.

Using other people’s code

A package can depend on other packages, usually from a Git repository. For example, Apple’s ArgumentParser library turns command-line arguments into typed options and generates --help text:

// In Package.swift
dependencies: [
    .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
],
targets: [
    .executableTarget(
        name: "calc",
        dependencies: [
            "Calculator",
            .product(name: "ArgumentParser", package: "swift-argument-parser"),
        ]
    ),
    // ...
]

from: "1.5.0" uses semantic versioning. Version numbers have three parts, major.minor.patch, with a promise attached: a new patch fixes bugs, a new minor version adds features, and only a new major version may break existing code. So from: "1.5.0" accepts any 1.x version from 1.5.0 on, but never 2.0.0. The versions actually chosen are recorded in Package.resolved; commit that file, so everyone building the project gets the same ones.

Where Swift goes from here

The same package structure runs Swift everywhere it runs:

  • Apps for iPhone, iPad, Mac, Apple Watch, and Vision Pro, usually with SwiftUI, in Xcode, which opens a package directly.
  • Servers, with frameworks such as Vapor and Hummingbird, on Linux.
  • Command-line tools and scripts, like calc.
  • Embedded systems, with Embedded Swift, a subset for microcontrollers.
  • Other platforms: Swift runs on Windows, and on Android and in WebAssembly through official SDKs.

And the ideas travel further than the language. Functions as values, recursion, abstraction barriers, algebraic data types, interpreters, and tests are the core of CS61A in any language, and the core of the courses that follow it. CS61B takes data structures and algorithms further; CS61C goes down to how machines actually run the code; CS162 builds the operating system underneath. The course notes on this site follow the same path.

Lab 23: Your own package

This lab builds the package from this lesson, step by step, in a terminal. There is nothing to paste into a single file this time: each step changes the package, and swift build and swift test check it.

Q0: What would Swift print?

What would Swift print?

struct Counter {
    private(set) var count = 0

    mutating func tap() {
        count += 1
    }
}

var counter = Counter()
counter.tap()
counter.tap()
counter.count = 10
print(counter.count)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

AnswerError

The program does not compile. private(set) lets any code read count, but only Counter’s own code can change it, and counter.count = 10 is outside. Without that line, it would print 2.

What would Swift print?

final class Box {
    fileprivate var secret = 7
}

func peek(_ box: Box) -> Int {
    box.secret * 6
}

print(peek(Box()))

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer42

fileprivate means visible anywhere in the same source file, and peek is in the same file as Box. In a package, a function in another file of the same module could not see secret.

Q1: Create the package

Create a library package named Calculator, then edit Package.swift to add an executable target calc that depends on the library, and an executable product for it. Check that swift build succeeds.

Show solution
mkdir Calculator
cd Calculator
swift package init --type library
mkdir -p Sources/calc
echo 'print("calc")' > Sources/calc/main.swift
swift build
swift run calc

The manifest is the one shown at the start of this lesson. A target’s sources are found by folder name, so creating Sources/calc and adding .executableTarget(name: "calc", dependencies: ["Calculator"]) is all the package manager needs. swift run calc builds and runs it, printing calc.

Q2: A library with a public face

Put Lesson 20’s calculator into Sources/Calculator/Calculator.swift. Change its errors to typed throws with CalcError, keep the tokenizer, parser, and evaluator internal, and make CalcError, calculate(_:), and run(_:) public, as shown in this lesson.

Show solution

The one change that needs care is evaluate, which used operands.map(evaluate). With typed throws, a loop keeps the error type exact and simple to read:

func evaluate(_ expr: Expr) throws(CalcError) -> Int {
    switch expr {
    case .number(let n):
        return n
    case .call(let op, let operands):
        var args: [Int] = []
        for operand in operands {
            args.append(try evaluate(operand))
        }
        return try apply(op, args)
    }
}

tokenize, parse, and apply change only in their signatures: throws(CalcError) instead of throws, and the same for the nested expression function in parse. Nothing else in them is public.

Q3: The command-line program

Write Sources/calc/main.swift so that swift run calc "(+ 1 2)" prints the result of its arguments, and swift run calc with no arguments starts a REPL that evaluates each line typed until the end of input.

Show solution

The program is the one in “A command-line program” above. To try both modes:

swift run calc "(- 10 1 2)"
printf '(+ 1 2)\n(/ 1 0)\n' | swift run calc

These print 7, then 3 and Error: division by zero. Joining the arguments with spaces means the quotes are optional for simple input: swift run calc 42 works too, though the shell would treat parentheses specially without them.

Q4: Tests

Replace the generated test file with tests for run and calculate: at least one success, one error from each stage (tokenizing cannot fail, so the parser and the evaluator), and one parameterized test. Run them with swift test.

Show solution

The tests in “Tests in a package” cover this. A test for a parser error, checked through calculate so that the exact error is compared:

@Test func missingParenthesis() {
    #expect(throws: CalcError("missing )")) {
        try calculate("(+ 1 (* 2 3)")
    }
}

Q5: A new feature, test first

Add a max operator to the calculator, working the way Lesson 20’s lab described. Write its tests first, run swift test to see them fail, then implement it. Finally, check with swift run calc "(max 3 9 2)".

Show solution
@Test(arguments: [("(max 3 9 2)", "9"), ("(max -4)", "-4"), ("(max)", "Error: max needs at least one operand")])
func maximum(input: String, expected: String) {
    #expect(run(input) == expected)
}

And the new case in apply:

case "max":
    guard let largest = args.max() else {
        throw CalcError("max needs at least one operand")
    }
    return largest

The tests fail first with Error: unknown operator max, which also confirms they are testing the right thing. A test that has never failed might not be testing anything.

Q6 (optional): Share it

Put the package in a Git repository with a tag such as 1.0.0, then create a second package that depends on it by URL (a local path works too: .package(path: "../Calculator")) and calls calculate from its own main.swift. Try calling tokenize from the second package, and read the error.

Show solution
// The second package's Package.swift
dependencies: [
    .package(path: "../Calculator"),
],
targets: [
    .executableTarget(
        name: "UsesCalculator",
        dependencies: [.product(name: "Calculator", package: "Calculator")]
    ),
]

calculate and run work, and tokenize gives “cannot find ‘tokenize’ in scope”: the library’s internal code is invisible from outside, as intended. With a tagged Git repository, anyone can depend on your library with .package(url:from:), and you can keep improving its internals without breaking them, as long as the public part keeps its promises.

What’s next

That is the end of the tutorial. You have gone from print("Hello, world!") to an interpreter, concurrent programs, a tested package, and three projects. The Swift book, linked from every lesson, covers every topic here in more depth, and the rest of this site continues with CS61B and beyond.