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

Concurrency

Estimate how long concurrent code takes, find a data race and fix it with an actor, spot a bug that hides across an await, and compute a maximum with a task group.

This discussion goes with Lesson 22.

Q1: What would Swift print?

What would Swift print?

func square(_ n: Int) async -> Int {
    try? await Task.sleep(for: .milliseconds(10 * (4 - n)))
    return n * n
}
async let a = square(1)
async let b = square(2)
async let c = square(3)
print(await [a, b, c])

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

Show answer and explanation

Answer[1, 4, 9]

c finishes first and a last, but the array lists the values in the order written. async let changes when work happens, never which value a name refers to.

What would Swift print?

actor Log {
    var entries: [String] = []
    func add(_ entry: String) {
        entries.append(entry)
    }
}
let log = Log()
await withTaskGroup(of: Void.self) { group in
    for word in ["a", "b", "c"] {
        group.addTask { await log.add(word) }
    }
}
print(await log.entries.sorted(), await log.entries.count)

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

Show answer and explanation

Answer["a", "b", "c"] 3

The order of the entries depends on which task runs first, so the program sorts them before printing. The count is always 3: the actor never loses an append.

Q2: How long does it take?

work(ms) sleeps for ms milliseconds and returns it. Roughly how long does each snippet take?

// 1
let x = await work(100)
let y = await work(200)

// 2
async let x = work(100)
async let y = work(200)
let total = await x + y

// 3
async let x = work(100)
let y = await work(200)
let total = await x + y

// 4
let total = await withTaskGroup(of: Int.self) { group in
    for ms in [100, 200, 300] {
        group.addTask { await work(ms) }
    }
    return await group.reduce(0, +)
}

// 5
var total = 0
for ms in [100, 200, 300] {
    total += await work(ms)
}
Show solution
  1. 300 ms. Each await waits for its call to finish before the next line starts.
  2. 200 ms. Both start immediately; the total waits for the slower one.
  3. 200 ms. x starts in the background, then the current task waits 200 for y, by which time x is long done.
  4. 300 ms, the slowest of the three, which all run at once. A task group is an async sequence, so reduce works on it.
  5. 600 ms. A loop with await inside is sequential, however the code looks.

Concurrent work takes about as long as the slowest piece; sequential work takes the sum.

Q3: Find the race

This code is meant to count words in several documents at once. Swift 6 refuses to compile it. Explain what could go wrong if it did compile, then fix it with an actor.

final class Tally {
    var counts: [String: Int] = [:]
}

let tally = Tally()
await withTaskGroup(of: Void.self) { group in
    for document in documents {
        group.addTask {
            for word in document.split(separator: " ") {
                tally.counts[String(word), default: 0] += 1
            }
        }
    }
}
Show solution

Several tasks may update tally.counts at the same moment. An update is a read (the old count), a change, and a write. If two tasks both read 4 for the same word, both write 5, and one count is lost. Worse, a dictionary that is changed by two tasks at once can corrupt its storage and crash. Swift 6 rejects the code because Tally is a class with mutable state, so it is not Sendable, and it is captured by tasks that may run in parallel.

actor Tally {
    private(set) var counts: [String: Int] = [:]

    func add(_ words: [String]) {
        for word in words {
            counts[word, default: 0] += 1
        }
    }
}

let documents = ["the cat sat", "the dog sat", "a cat"]
let tally = Tally()
await withTaskGroup(of: Void.self) { group in
    for document in documents {
        group.addTask {
            await tally.add(document.split(separator: " ").map(String.init))
        }
    }
}
let counts = await tally.counts
assert(counts["the"] == 2 && counts["cat"] == 2 && counts["sat"] == 2 && counts.count == 5)

Passing each document’s whole list of words in one call also means one hop onto the actor per document instead of one per word.

Q4: A bug across an await

This actor sells concert tickets. Each purchase checks that tickets remain, then asks a payment service, which takes time, and then hands out a ticket. It sometimes sells more tickets than exist. Why, when an actor runs only one task at a time? How would you fix it?

actor BoxOffice {
    var remaining = 100

    func buy(card: String) async throws -> Int {
        guard remaining > 0 else {
            throw SoldOut()
        }
        try await charge(card)          // takes a while
        remaining -= 1
        return remaining
    }
}
Show solution

An actor runs one task at a time only between suspension points. At await charge(card), the buy call suspends, and the actor is free to start other calls to buy. With one ticket left, ten buyers can all pass the guard before any of them reaches remaining -= 1, and remaining ends at −9.

The fix is to change the state before suspending, and undo it if the payment fails:

struct SoldOut: Error {}
struct Declined: Error {}

func charge(_ card: String) async throws {
    try await Task.sleep(for: .milliseconds(10))
    if card == "bad" {
        throw Declined()
    }
}

actor BoxOffice {
    private(set) var remaining: Int

    init(tickets: Int) {
        remaining = tickets
    }

    func buy(card: String) async throws -> Int {
        guard remaining > 0 else {
            throw SoldOut()
        }
        remaining -= 1                  // reserve before suspending
        do {
            try await charge(card)
        } catch {
            remaining += 1              // give it back
            throw error
        }
        return remaining
    }
}

let office = BoxOffice(tickets: 3)
let sold = await withTaskGroup(of: Bool.self) { group in
    for i in 0..<10 {
        group.addTask { (try? await office.buy(card: i == 0 ? "bad" : "card \(i)")) != nil }
    }
    return await group.reduce(0) { $0 + ($1 ? 1 : 0) }
}
let left = await office.remaining
assert(left >= 0 && sold + left == 3)

The test checks what must hold in every run. Usually all three tickets sell, but not always: if the declined card holds a reservation at the moment the others check, some of them are turned away, and its ticket comes back afterwards. What can never happen is selling a ticket that does not exist.

This is the actor rule from Lesson 22’s callout: after every await, the actor’s state may have changed, so a check made before it cannot be trusted after it.

Q5: The largest result

Write largest(_:_:), which applies an async function to every element concurrently and returns the largest result, or nil for no elements. Do not keep all the results: track the largest as they arrive.

Show solution
func largest(_ items: [Int], _ score: @escaping @Sendable (Int) async -> Int) async -> Int? {
    await withTaskGroup(of: Int.self) { group in
        for item in items {
            group.addTask { await score(item) }
        }
        var best: Int?
        for await value in group {
            best = max(best ?? value, value)
        }
        return best
    }
}

let best = await largest([3, 1, 4, 1, 5, 9, 2, 6]) { n in
    try? await Task.sleep(for: .milliseconds(n))
    return (n * 7) % 10
}
let none = await largest([]) { $0 }
assert(best == 8)   // 4 gives 28 % 10 = 8
assert(none == nil)

The order in which results arrive does not matter, because the maximum of a collection does not depend on order. Operations like this, where the order of combining makes no difference, are the ones that parallelize most easily.