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

Data-driven apps with SwiftUI

Apps whose screens follow a changing model: macros, the @Observable model and how SwiftUI tracks what a view reads, lists with search, navigation, charts with Swift Charts, and loading data asynchronously.

CS61B
For Project 4: NGordNet
Swift book
Macros · Properties

Lesson 26’s views owned small pieces of state with @State. Project 9 needs more: a collection of word histories loaded from files, a list you can search, a screen for each word, and charts of how often words were used over two centuries. This lesson covers the SwiftUI for that kind of app, in which one model holds the data, and many views show parts of it and stay up to date by themselves.

Macros

This lesson’s central tool is written @Observable, and it is a macro. The Swift book’s chapter on macros describes them: code that runs at compile time to generate more code, which is then compiled as if you had written it.

  • A freestanding macro stands on its own and starts with #. You have used #expect (Lesson 23), #Preview (Lesson 26), and #line is a built-in relative.
  • An attached macro starts with @ and modifies the declaration it is attached to, adding members, conformances, or code around properties.

Macros are ordinary Swift packages that transform the syntax tree of your code. The expansion is type-checked like any other code, and in Xcode you can right-click a macro and choose Expand Macro to see exactly what it generates. Writing your own macro is beyond this course; using them well requires only knowing what they expand to.

Observable models

A model is usually a class, because many views share it. Marking it with the @Observable macro makes SwiftUI track which properties each view reads, and update exactly those views when those properties change:

import Observation

@Observable
final class WordLibrary {
    var words = ["swift", "sparrow", "owl"]
    var searchText = ""

    var visibleWords: [String] {
        searchText.isEmpty ? words : words.filter { $0.contains(searchText) }
    }
}

let library = WordLibrary()
var changes = 0

func watch() {
    withObservationTracking {
        _ = library.visibleWords        // reads words and searchText
    } onChange: {
        changes += 1
    }
}

watch()
library.searchText = "sw"               // a tracked property changed
watch()
library.words.append("swan")            // so did this one
print(changes, library.visibleWords)    // 2 ["swift", "swan"]

withObservationTracking is the mechanism SwiftUI itself uses, shown here without SwiftUI. It runs the first closure and records every observable property it reads, even through a computed property like visibleWords. When any of them changes, onChange runs once, and tracking ends, which is why watch() is called again. SwiftUI does the same with each view’s body: it records what the body reads, and when something changes, it computes the body again, which records the new set of dependencies.

What the @Observable macro generates is the bookkeeping: each stored property becomes a computed property whose getter reports “read” and whose setter reports “changed”, plus a hidden registrar that tracks them. The class also conforms to the Observable protocol.

Sharing a model with views

A view that creates a model owns it with @State, as with any other state. Views that only use it can take it as a plain property, or find it in the environment, a set of values that SwiftUI passes down the view hierarchy:

import SwiftUI

@Observable
final class WordLibrary {
    var words = ["swift", "sparrow", "owl"]
    var searchText = ""
    var visibleWords: [String] {
        searchText.isEmpty ? words : words.filter { $0.localizedStandardContains(searchText) }
    }
}

struct LibraryScreen: View {
    @State private var library = WordLibrary()      // this view owns the model

    var body: some View {
        WordList()
            .environment(library)                   // available to everything below
    }
}

struct WordList: View {
    @Environment(WordLibrary.self) private var library

    var body: some View {
        @Bindable var library = library             // for the $ binding below
        List(library.visibleWords, id: \.self) { word in
            Text(word)
        }
        .searchable(text: $library.searchText)
    }
}

@Bindable makes bindings, the $ projections from Lesson 26, to the properties of an observable object that the view did not create. Here .searchable needs a binding to searchText, so that typing in the search field changes the model; the list reads visibleWords, so it updates as you type.

Lists and navigation

List shows rows, and ForEach makes one view per item of a collection. Both need to tell items apart across updates, so that SwiftUI can animate insertions and keep selection right: either id: \.self for values that are their own identity, or items that conform to Identifiable, with an id property.

NavigationStack pushes screens: a NavigationLink(value:) in a list row, and a .navigationDestination(for:) that says which view shows a value of that type:

import SwiftUI

struct Word: Identifiable, Hashable {
    let text: String
    let counts: [Int: Int]          // year → number of uses
    var id: String { text }
}

struct WordsScreen: View {
    let words: [Word]

    var body: some View {
        NavigationStack {
            List(words) { word in
                NavigationLink(word.text, value: word)
            }
            .navigationTitle("Words")
            .navigationDestination(for: Word.self) { word in
                Text("\(word.text): \(word.counts.values.reduce(0, +)) uses")
                    .navigationTitle(word.text)
            }
        }
    }
}

Navigating by value keeps the navigation state as data: a path of values that the program can inspect, change, or save, like any other state.

Charts

Swift Charts draws charts from data, declaratively, in the same style as views. A chart is a set of marks, each mapping values to visual positions:

import Charts
import SwiftUI

struct YearCount: Identifiable {
    let year: Int
    let count: Int
    var id: Int { year }
}

struct HistoryChart: View {
    let word: String
    let points: [YearCount]

    var body: some View {
        Chart(points) { point in
            LineMark(
                x: .value("Year", point.year),
                y: .value("Uses", point.count)
            )
            .foregroundStyle(by: .value("Word", word))
        }
        .chartXAxisLabel("Year")
        .chartYAxisLabel("Uses per million words")
        .frame(minHeight: 240)
    }
}

LineMark connects the points; BarMark, PointMark, and AreaMark draw the same data in other ways. .value("Year", …) names each dimension, which labels the axes and the legend. Coloring by word means several words’ lines can share one chart, each in its own color, with a legend generated automatically, which Project 9 uses to compare words.

Loading data

Real data arrives from files or the network, and loading takes time. The model records where loading has got to, with Lesson 19’s favorite tool, an enum:

import SwiftUI

enum Loading<Value> {
    case loading
    case loaded(Value)
    case failed(String)
}

struct LoadingView: View {
    @State private var state: Loading<[String]> = .loading

    var body: some View {
        Group {
            switch state {
            case .loading:
                ProgressView("Loading words…")
            case .loaded(let words):
                List(words, id: \.self) { Text($0) }
            case .failed(let message):
                ContentUnavailableView("Could not load words", systemImage: "exclamationmark.triangle",
                                       description: Text(message))
            }
        }
        .task {
            do {
                try await Task.sleep(for: .milliseconds(300))      // stand-in for reading a file
                state = .loaded(["swift", "sparrow", "owl"])
            } catch {
                state = .failed("cancelled")
            }
        }
    }
}

The view’s body is a switch over the state, so every situation has a screen, and the compiler checks that none is forgotten. .task starts loading when the view appears and cancels it if the view goes away, as in Lesson 26.

Put the lines in order

Put the lines in order so the program prints 1.

  1. var value = 0
  2. }
  3. @Observable final class Counter {
  4. var changes = counter.value
  5. counter.value = 5
  6. import Observation
  7. withObservationTracking { _ = counter.value } onChange: { changes += 1 }
  8. let counter = Counter()
  9. print(changes)

Show the correct program
import Observation
@Observable final class Counter {
    var value = 0
}
let counter = Counter()
var changes = counter.value
withObservationTracking { _ = counter.value } onChange: { changes += 1 }
counter.value = 5
print(changes)

Lab 41: Data-driven apps

The model problems run as scripts. The SwiftUI problems need a Mac; put them in an app package as in Lesson 26.

Q0: What would Swift print?

What would Swift print?

import Observation
@Observable final class Settings {
    var volume = 5
    var theme = "light"
}
let settings = Settings()
var changes = 0
withObservationTracking {
    _ = settings.volume
} onChange: {
    changes += 1
}
settings.theme = "dark"
settings.volume = 7
settings.volume = 9
print(changes)

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

Show answer and explanation

Answer1

The tracked closure read only volume, so changing theme does not count. Changing volume fires onChange once, and ends the tracking, so the second change is not reported. SwiftUI re-registers after each update; code using withObservationTracking directly must do the same.

Q1: A model with derived data

Write an @Observable class WordHistory holding a dictionary from word to its yearly counts ([String: [Int: Int]]), a selected set of words, and computed properties totalUses(of:) and selectedSeries, which returns, for each selected word in alphabetical order, its (year, count) pairs sorted by year. Check with withObservationTracking that reading selectedSeries tracks selected.

Show solution
import Observation

@Observable
final class WordHistory {
    var counts: [String: [Int: Int]] = [:]
    var selected: Set<String> = []

    func totalUses(of word: String) -> Int {
        counts[word, default: [:]].values.reduce(0, +)
    }

    var selectedSeries: [(word: String, points: [(year: Int, count: Int)])] {
        selected.sorted().map { word in
            let points = counts[word, default: [:]].sorted { $0.key < $1.key }.map { (year: $0.key, count: $0.value) }
            return (word, points)
        }
    }
}

let history = WordHistory()
history.counts = ["swift": [2000: 3, 1990: 1], "owl": [1990: 5]]
history.selected = ["swift"]

var changed = false
withObservationTracking {
    _ = history.selectedSeries
} onChange: {
    changed = true
}
history.selected.insert("owl")

assert(changed)
assert(history.totalUses(of: "swift") == 4)
assert(history.selectedSeries.map(\.word) == ["owl", "swift"])
assert(history.selectedSeries[1].points.map(\.year) == [1990, 2000])

Derived data belongs in computed properties, not in stored copies that would have to be kept in sync. Observation sees through them: reading selectedSeries reads selected and counts, and a change to either is reported.

Q2: A searchable list

Write a view that shows the words of a WordHistory-like model in a searchable list, each row showing the word and its total uses, sorted by total uses, most first.

Show solution
import SwiftUI

@Observable
final class WordStore {
    var totals: [String: Int] = ["swift": 40, "owl": 12, "sparrow": 25]
    var searchText = ""

    var rows: [(word: String, total: Int)] {
        totals
            .filter { searchText.isEmpty || $0.key.localizedStandardContains(searchText) }
            .sorted { $0.value > $1.value }
            .map { (word: $0.key, total: $0.value) }
    }
}

struct SearchableWords: View {
    @State private var store = WordStore()

    var body: some View {
        NavigationStack {
            List(store.rows, id: \.word) { row in
                LabeledContent(row.word, value: row.total, format: .number)
            }
            .navigationTitle("Words")
            .searchable(text: $store.searchText)
        }
    }
}

LabeledContent lays out a label and a value the way the platform expects, and format: .number formats the count for the user’s locale. Because this view owns the store with @State, $store.searchText works without @Bindable.

Q3: A chart of several words

Write a view that charts the yearly counts of several words at once, one colored line per word, with points marked, given [(word: String, points: [(year: Int, count: Int)])].

Show solution
import Charts
import SwiftUI

struct MultiWordChart: View {
    let series: [(word: String, points: [(year: Int, count: Int)])]

    var body: some View {
        Chart {
            ForEach(series, id: \.word) { item in
                ForEach(item.points, id: \.year) { point in
                    LineMark(x: .value("Year", point.year), y: .value("Uses", point.count))
                        .foregroundStyle(by: .value("Word", item.word))
                    PointMark(x: .value("Year", point.year), y: .value("Uses", point.count))
                        .foregroundStyle(by: .value("Word", item.word))
                }
            }
        }
        .chartLegend(position: .bottom)
        .frame(minHeight: 260)
    }
}

Grouping by .foregroundStyle(by:) does two things: each word gets its own color, and the line marks with the same word are connected into one line rather than all points into a single zigzag.

Q4: Loading with failure

Write a model with a Loading<[String: Int]> state and an async method load() that sleeps briefly and then either fills the state or, if a flag says so, fails with a message. Write a view that shows each state and a Retry button on failure.

Show solution
import SwiftUI

enum Loading<Value> {
    case loading
    case loaded(Value)
    case failed(String)
}

@Observable
final class Loader {
    var state: Loading<[String: Int]> = .loading
    var shouldFail = true

    func load() async {
        state = .loading
        try? await Task.sleep(for: .milliseconds(200))
        if shouldFail {
            shouldFail = false                   // succeed next time
            state = .failed("the data file is missing")
        } else {
            state = .loaded(["swift": 40, "owl": 12])
        }
    }
}

struct LoaderView: View {
    @State private var loader = Loader()

    var body: some View {
        Group {
            switch loader.state {
            case .loading:
                ProgressView()
            case .loaded(let totals):
                List(totals.sorted { $0.key < $1.key }, id: \.key) { entry in
                    LabeledContent(entry.key, value: entry.value, format: .number)
                }
            case .failed(let message):
                VStack {
                    Text(message)
                    Button("Retry") { Task { await loader.load() } }
                        .buttonStyle(.glassProminent)
                }
            }
        }
        .task { await loader.load() }
    }
}

Putting the loading logic in the model keeps the view a pure description of the state, and makes the logic testable with Swift Testing, without a window.

What’s next

Next lesson: graphs, the most general way to represent connections, and the traversals that explore them.