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

Computing, society, and what comes next

The people on the other side of the code: accessibility, privacy and why hashing is not anonymity, fairness in rankings, working with AI tools responsibly, and a look back over the whole tutorial with where to go next.

CS61B
Social Implications of Computing · AI in Software Engineering · Summary · Textbook Ch. 35, Ch. 36
Swift book
A Swift Tour
Documentation
Swift documentation

CS61B ends with two lectures that are not about data structures: one on the social implications of computing, and one on how AI tools are changing software engineering. Both make the same point from different sides. Programs are used by people, affect people who never use them, and are increasingly written with help from systems that can be wrong in convincing ways. This lesson covers both, with the parts that turn into code, and then looks back over the whole tutorial.

Software reaches people who did not choose it

A ranking algorithm decides which job applications a recruiter sees. A map’s routing sends traffic down residential streets. A content filter decides which messages count as spam. The people affected rarely see the code, and often do not know it exists. That puts responsibility on the people who write it, in three recurring areas.

Accessibility

Around a billion people have a disability. Apple’s platforms include VoiceOver, which reads the screen aloud; a SwiftUI app is accessible by default for standard controls, and needs help only where the meaning is visual:

import SwiftUI

struct Palette: View {
    @State private var selected = "sand"
    let colors: [(name: String, color: Color)] = [("sand", .yellow), ("water", .blue), ("fire", .red)]

    var body: some View {
        HStack {
            ForEach(colors, id: \.name) { item in
                Button {
                    selected = item.name
                } label: {
                    Circle().fill(item.color).frame(width: 24, height: 24)
                }
                .accessibilityLabel(item.name)
                .accessibilityAddTraits(selected == item.name ? .isSelected : [])
            }
        }
        .buttonStyle(.glass)
    }
}

Without the label, VoiceOver would announce each button as “button”, and Project 5’s palette would be unusable without sight. Other habits cost little: support Dynamic Type instead of fixed font sizes, do not rely on color alone to carry meaning, and try your app with VoiceOver on.

Privacy

The safest data is data that was never collected. Collect only what the feature needs, keep it only as long as needed, and remember that data outlives the purpose it was collected for. A frequent mistake is to think that hashing anonymizes data:

func weakHash(_ s: String) -> Int {
    s.utf8.reduce(0) { $0 &* 31 &+ Int($1) }
}

// A "pseudonymous" dataset: four-digit PINs replaced by their hashes.
let published = [weakHash("4821"), weakHash("0937")]

// Anyone can hash every possible PIN and look the hashes up.
var recovered: [String] = []
for n in 0...9999 {
    let digits = String(n)
    let candidate = String(repeating: "0", count: 4 - digits.count) + digits
    if published.contains(weakHash(candidate)) { recovered.append(candidate) }
}
print(recovered)   // ["0937", "4821"]

When the set of possible values is small enough to enumerate, as PINs, phone numbers, ages, or postcodes are, a hash is just a lookup away from the original. Real re-identification attacks combine several such fields. Strong hashing with a secret key helps, but the real protection is not publishing or storing what is not needed.

Fairness

A system can be unfair without any line of code mentioning a person’s group, when the data it learns from or the proxies it uses correlate with group membership. The first step is to measure: compute outcomes separately for each group, and look at the differences.

struct Applicant {
    let group: String
    let score: Int
}

func selectionRates(_ applicants: [Applicant], threshold: Int) -> [String: Double] {
    Dictionary(grouping: applicants, by: \.group).mapValues { members in
        Double(members.filter { $0.score >= threshold }.count) / Double(members.count)
    }
}

let applicants = [Applicant(group: "A", score: 82), Applicant(group: "A", score: 75), Applicant(group: "A", score: 91),
                  Applicant(group: "B", score: 68), Applicant(group: "B", score: 88), Applicant(group: "B", score: 71)]
let rates = selectionRates(applicants, threshold: 74)
print(rates["A"]!, rates["B"]!)   // 1.0 0.3333333333333333

Numbers like these do not say why rates differ, and there are several mathematical definitions of fairness that cannot all hold at once. But a system whose outcomes are never measured by group can be unfair for years without anyone noticing. Measure, publish how the system works, and give people a way to contest its decisions.

What would Swift print?

let ages = 0...120
let target = 37
let hidden = target.hashValue
let found = ages.first { $0.hashValue == hidden }
print(found!)

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

Show answer and explanation

Answer37

Even Swift’s strong, randomly seeded Hasher does not hide a value from someone who can compute hashes in the same process and try every possibility. With only 121 possible ages, the search is instant.

Working with AI tools

AI coding assistants can write plausible code quickly, explain unfamiliar APIs, and draft tests. CS61B’s lecture on AI in software engineering asks what changes, and what does not. What does not change: you are responsible for the code you ship, and everything in this tutorial about understanding code still applies. In practice:

  • Read and understand generated code before using it, as if a colleague had written it. If you could not have written it, you cannot tell whether it is right.
  • Test it, especially the edge cases generated code tends to miss: empty inputs, duplicates, the boundaries of Lesson 23. The randomized comparison tests of Lesson 27 are an excellent check on generated data structures.
  • Check its claims against sources. Generated explanations can cite functions, options, and guarantees that do not exist. Look them up in the documentation, as this tutorial does for every API it links.
  • Keep learning the fundamentals. A tool that writes a red-black tree does not tell you when you need one. Knowing what is possible and what it costs is what lets you ask for the right thing and recognize a wrong answer.

The projects in this course are designed so that the learning is in doing them. Using a tool to finish them without understanding defeats their purpose, whatever the result.

Put the lines in order

Put the lines in order so the program prints 0.5.

  1. print(rate)
  2. let rate = Double(selected) / Double(outcomes.count)
  3. let selected = outcomes.filter { $0 }.count
  4. let outcomes = [true, false, true, false]

Show the correct program
let outcomes = [true, false, true, false]
let selected = outcomes.filter { $0 }.count
let rate = Double(selected) / Double(outcomes.count)
print(rate)

Looking back

Fifty-nine lessons ago, this tutorial started with print("Hello, world!"). It then followed two Berkeley courses:

  • Units 1 to 3, CS61A: functions and higher-order functions, environments and closures, recursion, data abstraction, sequences and containers, objects and mutation, protocols and generics, lazy evaluation, efficiency, algebraic data types, an interpreter, errors, concurrency, testing, and packages. Four projects: Hog, Cats, Ants, and Scheme.
  • Units 4 to 7, CS61B: references and memory, linked lists and array lists built from scratch, interfaces and inheritance, iteration and copy-on-write, asymptotic analysis, disjoint sets, search trees, heaps, graphs and their algorithms, hashing, tries, sorting and its limits, compression, and software engineering. Six projects: Particle Simulator, two deques, Percolation, NGordNet, and Build Your Own World.

Along the way, the whole of The Swift Programming Language and a good part of SwiftUI.

Where to go next

  • CS61C, Great Ideas in Computer Architecture: how the programs you write become machine instructions, memory, caches, and parallel hardware. It explains why Lesson 30’s arrays were 40 times faster than linked lists.
  • CS162, Operating Systems: processes, threads, scheduling, file systems, and the concurrency problems that Lesson 22’s actors avoid.
  • CS170, Efficient Algorithms: dynamic programming, network flow, linear programming, and NP-completeness in depth.
  • Building things: an app with SwiftUI, a server with Swift on Linux, or a contribution to an open-source Swift package. The best way to keep what you learned is to use it on something you care about.

Notes for the next courses are on this site. Thank you for learning with it.

Lab 58: Responsibility

Q0: What would Swift print?

What would Swift print?

let scores = ["A": [90, 80, 70], "B": [60, 95]]
let averages = scores.mapValues { $0.reduce(0, +) / $0.count }
print(averages["A"]!, averages["B"]!)

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

Show answer and explanation

Answer80 77

Integer division truncates: 155 / 2 is 77. An average hides the spread, too: group B has the single highest score. Summaries that drive decisions deserve a second look at how they are computed.

Q1: Accessible labels

Take Lesson 52’s game view and make it usable with VoiceOver: give the canvas an accessibility label describing the avatar’s position and the flowers picked, updated as the game changes.

Show solution
import SwiftUI

struct AccessibleGameView: View {
    @State private var row = 1
    @State private var column = 1
    @State private var flowersPicked = 0

    var body: some View {
        Canvas { context, size in
            let side = size.width / 7
            context.fill(Path(ellipseIn: CGRect(x: CGFloat(column) * side, y: CGFloat(row) * side, width: side, height: side)),
                         with: .color(.yellow))
        }
        .accessibilityElement()
        .accessibilityLabel("Game world")
        .accessibilityValue("Avatar at row \(row + 1), column \(column + 1). \(flowersPicked) flowers picked.")
        .accessibilityHint("Use the W, A, S, and D keys to move.")
        .frame(width: 280, height: 200)
    }
}

A canvas is one image to VoiceOver, so it needs a label saying what it is and a value saying its current state. Because the value is computed from the state, it updates whenever the avatar moves, like everything else in a SwiftUI view.

Q2: Minimizing data

A sign-up form collects a full name, a date of birth, an email address, a phone number, and a postcode, to let users log in and to check that they are over 13. Write a Profile type that stores only what those two purposes need, and a function that derives it from the form.

Show solution
struct SignUpForm {
    let fullName: String
    let birthYear: Int
    let birthMonth: Int
    let birthDay: Int
    let email: String
    let phone: String
    let postcode: String
}

struct Profile: Equatable {
    let email: String            // to log in
    let isOver13: Bool           // the only fact the age check needs
}

func profile(from form: SignUpForm, today: (year: Int, month: Int, day: Int)) -> Profile {
    var age = today.year - form.birthYear
    if (today.month, today.day) < (form.birthMonth, form.birthDay) { age -= 1 }
    return Profile(email: form.email, isOver13: age >= 13)
}

let form = SignUpForm(fullName: "Ada Lovelace", birthYear: 2013, birthMonth: 12, birthDay: 10,
                      email: "ada@example.com", phone: "0912-345-678", postcode: "10617")
assert(profile(from: form, today: (2026, 9, 27)) == Profile(email: "ada@example.com", isOver13: false))
assert(profile(from: form, today: (2026, 12, 10)).isOver13)

The stored profile cannot leak a birth date, a phone number, or a postcode, because it never had them. The age check keeps a single boolean, derived at sign-up. Collecting less is a design decision, made in the types.

Q3 (optional): Reviewing generated code

An assistant produced this function to return the median of an array, with the explanation “sorts the array and returns the middle element, O(n)”. Find everything wrong with the code and the explanation, and fix it.

func median(_ values: [Double]) -> Double {
    let sorted = values.sorted()
    return sorted[sorted.count / 2]
}
Show solution
  • The explanation’s cost is wrong: sorting is O(n log n), not O(n). Lesson 55’s quickselect would give O(n) on average.
  • For an even number of values, the median is the average of the two middle ones; this returns the upper one.
  • An empty array crashes, with no documented precondition.
func median(_ values: [Double]) -> Double? {
    guard !values.isEmpty else { return nil }
    let sorted = values.sorted()
    let middle = sorted.count / 2
    return sorted.count % 2 == 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2
}

assert(median([3, 1, 2]) == 2)
assert(median([4, 1, 3, 2]) == 2.5)
assert(median([]) == nil)

Three small tests, an odd count, an even count, and the empty array, found all the bugs. The same review applies to code from any source.

The end

That is the whole tutorial. Build something.