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

Classes and inheritance

Reference types for things that should be shared: CS61A’s bank account as a class, identity with ===, type properties, subclasses that override behavior, and object lifetimes.

CS61A
Classes · Inheritance · Composing Programs 2.5–2.7

A bank account is not a value to be copied. If two people share an account, a deposit by one must be visible to the other. Things like that, with an identity and a state that changes over time, are objects, and Swift models them with classes.

Defining a class

CS61A’s example is the bank account. A class looks much like a structure:

class Account {
    let holder: String
    var balance = 0

    init(holder: String) {
        self.holder = holder
    }

    func deposit(_ amount: Int) -> Int {
        balance += amount
        return balance
    }

    func withdraw(_ amount: Int) -> Int {
        if amount > balance {
            print("Insufficient funds")
            return balance
        }
        balance -= amount
        return balance
    }
}

let account = Account(holder: "Ada")
print(account.deposit(100))   // 100
print(account.withdraw(30))   // 70

Two differences from a structure show up already. A class has no automatic memberwise initializer, so init must set every property that has no default. And deposit changes balance without being marked mutating, even though account was bound with let.

Reference semantics

That second difference is the important one. A class is a reference type: a variable holds a reference to an object, and assigning it copies the reference, not the object.

What would Swift print?

class Account {
    var balance = 0
}
let mine = Account()
let ours = mine
ours.balance += 10
print(mine.balance)

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

Show answer and explanation

Answer10

mine and ours refer to the same object, so a change made through ours is visible through mine. This is Python’s aliasing, on purpose. The let means the reference cannot change; the object it refers to still can.

=== asks whether two references point to the same object. == is not available unless the class defines what equality means:

class Account {
    var balance = 0
}

let a = Account()
let b = a
let c = Account()
print(a === b, a === c)   // true false

c is a different account that happens to have the same balance. Identity and equality are different questions, and with classes you need to know which one you are asking.

Type properties

A property marked static belongs to the class itself, not to any one object. CS61A uses a class attribute for the interest rate shared by every account:

class Account {
    static let interestRate = 0.02
    var balance = 0
}

print(Account.interestRate)   // 0.02

Structures and enumerations can have static properties too.

Inheritance

A subclass is a class defined in terms of another, its superclass. It gets all of the superclass’s properties and methods, and can override some of them. A checking account is an account that charges a fee for withdrawals:

class Account {
    var balance = 0

    func deposit(_ amount: Int) -> Int {
        balance += amount
        return balance
    }

    func withdraw(_ amount: Int) -> Int {
        if amount > balance {
            print("Insufficient funds")
            return balance
        }
        balance -= amount
        return balance
    }
}

class CheckingAccount: Account {
    static let withdrawFee = 1

    override func withdraw(_ amount: Int) -> Int {
        super.withdraw(amount + CheckingAccount.withdrawFee)
    }
}

let checking = CheckingAccount()
_ = checking.deposit(20)
print(checking.withdraw(5))   // 14

override is required, so you cannot replace a method by accident. super.withdraw calls the superclass’s version, reusing its logic rather than copying it.

What would Swift print?

class Account {
    var balance = 0
    func withdraw(_ amount: Int) -> Int {
        if amount > balance {
            print("Insufficient funds")
            return balance
        }
        balance -= amount
        return balance
    }
}
class CheckingAccount: Account {
    override func withdraw(_ amount: Int) -> Int {
        super.withdraw(amount + 1)
    }
}
let checking = CheckingAccount()
checking.balance = 20
print(checking.withdraw(5), checking.withdraw(100))

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

Show answer and explanation

AnswerInsufficient funds\n14 14

Both arguments to print are evaluated before anything is printed. The first withdrawal takes 5 plus the fee, leaving 14. The second asks for 101, which prints “Insufficient funds” immediately and returns 14 unchanged. Only then does print write 14 14.

A variable of the superclass type can hold a subclass object, and calling a method runs the version for the object’s actual class:

class Account {
    var balance = 0
    func withdraw(_ amount: Int) -> Int { balance -= amount; return balance }
}
class CheckingAccount: Account {
    override func withdraw(_ amount: Int) -> Int { super.withdraw(amount + 1) }
}

let accounts: [Account] = [Account(), CheckingAccount()]
for account in accounts {
    account.balance = 10
    print(account.withdraw(3))   // 7, then 6
}

Initializing a subclass

A subclass that adds stored properties needs its own initializer. It must set its own properties first, then call super.init to let the superclass set the rest:

class Animal {
    let name: String
    init(name: String) {
        self.name = name
    }
    func speak() -> String { "..." }
}

class Dog: Animal {
    let tricks: [String]
    init(name: String, tricks: [String]) {
        self.tricks = tricks          // this class's property first
        super.init(name: name)        // then the superclass
    }
    override func speak() -> String { "woof" }
}

let pets: [Animal] = [Animal(name: "Generic"), Dog(name: "Rex", tricks: ["sit"])]
print(pets.map { $0.speak() })             // ["...", "woof"]
print(pets[1] is Dog, pets[0] is Dog)      // true false
print((pets[1] as? Dog)?.tricks ?? [])     // ["sit"]

is checks an object’s actual class, and as? converts to a subclass if it really is one, giving an optional. Needing many such checks is often a sign that the behavior belongs in an overridden method instead.

Put the lines in order

Put the lines in order so the program prints 14.

  1. var balance = 0
  2. }
  3. func withdraw(_ amount: Int) -> Int {
  4. override func withdraw(_ amount: Int) -> Int {
  5. print(checking.withdraw(5))
  6. let checking = CheckingAccount()
  7. super.withdraw(amount + 1)
  8. }
  9. return balance
  10. }
  11. balance -= amount
  12. class CheckingAccount: Account {
  13. checking.balance = 20
  14. }
  15. class Account {

Show the correct program
class Account {
    var balance = 0
    func withdraw(_ amount: Int) -> Int {
        balance -= amount
        return balance
    }
}
class CheckingAccount: Account {
    override func withdraw(_ amount: Int) -> Int {
        super.withdraw(amount + 1)
    }
}
let checking = CheckingAccount()
checking.balance = 20
print(checking.withdraw(5))

Object lifetimes

Swift frees an object automatically when nothing refers to it any more, using automatic reference counting (ARC). A class can run code at that moment in a deinitializer:

class Tracker {
    let name: String
    init(_ name: String) {
        self.name = name
        print("hello", name)
    }
    deinit {
        print("bye", name)
    }
}

do {
    let tracker = Tracker("t")
    print("using", tracker.name)
}
print("after")

The do block makes a scope. When it ends, the last reference to the tracker disappears, so “bye t” is printed before “after”. Two objects that refer to each other can keep each other alive forever; the Swift book’s Automatic Reference Counting chapter explains how weak references break such cycles.

Reference cycles

ARC frees an object when no references to it remain. Two objects that refer to each other always have one reference left, so neither is ever freed:

class Person {
    let name: String
    var friend: Person?
    init(_ name: String) { self.name = name }
    deinit { print("goodbye", name) }
}

do {
    let ada = Person("Ada")
    let grace = Person("Grace")
    ada.friend = grace
    grace.friend = ada
}
print("after the block")   // no goodbyes: both objects leaked

Marking one side weak var friend: Person? fixes it. A weak reference does not keep its object alive, and becomes nil when the object goes away, which is why it must be an optional. With weak, both goodbyes print when the block ends.

Lab 14: Objects

Q0: What would Swift print?

What would Swift print?

class Counter {
    var count = 0
}
func bump(_ c: Counter) {
    c.count += 1
}
let c = Counter()
bump(c)
bump(c)
print(c.count)

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

Show answer and explanation

Answer2

The function receives a reference to the same object, so its changes stick, with no inout needed. Compare the structure version in Lesson 14, where the parameter was a constant copy.

What would Swift print?

class Shape {
    func name() -> String { "shape" }
    func describe() -> String { "a " + name() }
}
class Square: Shape {
    override func name() -> String { "square" }
}
print(Square().describe(), Shape().describe())

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

Show answer and explanation

Answera square a shape

describe is inherited, but the name() it calls is looked up on the actual object. For a square, that is the overridden version.

What would Swift print?

class Account {
    var balance = 0
}
var accounts = [Account(), Account()]
let first = accounts[0]
first.balance = 50
print(accounts[0].balance, accounts[1].balance)

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

Show answer and explanation

Answer50 0

The array holds references. first refers to the same object as accounts[0], so changing it changes what the array sees.

Q1: Vending machine

This is a CS61A lab classic. Write a VendingMachine class that sells one product at one price. It starts with no stock and no funds.

  • restock(_:) adds stock and returns "Current <product> stock: <n>".
  • addFunds(_:) returns "Current balance: $<n>", but if the machine is empty it keeps nothing and returns "Nothing left to vend. Please restock. Here is your $<n>.".
  • vend() returns "Nothing left to vend. Please restock." when empty, "Please add $<n> more funds." when short, and otherwise sells one item, returning "Here is your <product>." or "Here is your <product> and $<n> change.". Change is returned, so the balance goes back to 0.
Show solution
class VendingMachine {
    let product: String
    let price: Int
    private var stock = 0
    private var funds = 0

    init(product: String, price: Int) {
        self.product = product
        self.price = price
    }

    func restock(_ amount: Int) -> String {
        stock += amount
        return "Current \(product) stock: \(stock)"
    }

    func addFunds(_ amount: Int) -> String {
        if stock == 0 {
            return "Nothing left to vend. Please restock. Here is your $\(amount)."
        }
        funds += amount
        return "Current balance: $\(funds)"
    }

    func vend() -> String {
        if stock == 0 {
            return "Nothing left to vend. Please restock."
        }
        if funds < price {
            return "Please add $\(price - funds) more funds."
        }
        let change = funds - price
        stock -= 1
        funds = 0
        return change > 0 ? "Here is your \(product) and $\(change) change." : "Here is your \(product)."
    }
}

let machine = VendingMachine(product: "candy", price: 10)
assert(machine.vend() == "Nothing left to vend. Please restock.")
assert(machine.addFunds(15) == "Nothing left to vend. Please restock. Here is your $15.")
assert(machine.restock(2) == "Current candy stock: 2")
assert(machine.vend() == "Please add $10 more funds.")
assert(machine.addFunds(7) == "Current balance: $7")
assert(machine.addFunds(5) == "Current balance: $12")
assert(machine.vend() == "Here is your candy and $2 change.")
assert(machine.addFunds(10) == "Current balance: $10")
assert(machine.vend() == "Here is your candy.")
assert(machine.addFunds(15) == "Nothing left to vend. Please restock. Here is your $15.")

private keeps stock and funds inside the class, so the only way to change them is through the three methods, which keep them consistent.

Q2: Savings with interest

Write SavingsAccount, a subclass of Account (as defined in this lesson, with deposit and withdraw), that adds a method addInterest() which increases the balance by Account.interestRate, rounded down to a whole number, and returns the new balance. Withdrawals from a savings account should be refused entirely (return the balance unchanged) when they would leave less than 10.

Show solution
class Account {
    static let interestRate = 0.02
    var balance = 0

    func deposit(_ amount: Int) -> Int {
        balance += amount
        return balance
    }

    func withdraw(_ amount: Int) -> Int {
        if amount > balance {
            return balance
        }
        balance -= amount
        return balance
    }
}

class SavingsAccount: Account {
    static let minimumBalance = 10

    func addInterest() -> Int {
        balance += Int(Double(balance) * Account.interestRate)
        return balance
    }

    override func withdraw(_ amount: Int) -> Int {
        if balance - amount < SavingsAccount.minimumBalance {
            return balance
        }
        return super.withdraw(amount)
    }
}

let savings = SavingsAccount()
assert(savings.deposit(500) == 500)
assert(savings.addInterest() == 510)
assert(savings.withdraw(505) == 510)   // would leave 5, refused
assert(savings.withdraw(500) == 10)

addInterest is new, so it needs no override; withdraw replaces an inherited method, so it does. Int(...) of a Double rounds toward zero.

Q3: Shared or copied?

Predict what this program prints, then run it.

struct PointValue {
    var x = 0
}
class PointObject {
    var x = 0
}

var v1 = PointValue()
var v2 = v1
v2.x = 5

let o1 = PointObject()
let o2 = o1
o2.x = 5

print(v1.x, o1.x)
Show solution

It prints 0 5. The structure is copied, so changing v2 leaves v1 at 0. The class instance is shared, so changing it through o2 is visible through o1. The two type definitions are identical except for one keyword.

Q4: Mint and coins

A CS61A lab classic. A Mint stamps each coin with its current year. A coin’s worth is its face value plus one cent for every year beyond 50 years old.

  • Mint.presentYear is a static var, starting at 2026.
  • A Mint records the present year when created; update() sets it to the present year again; create(_:) makes a coin of a given type with the mint’s year.
  • Coin subclasses Nickel and Dime have face values 5 and 10.
Show solution
class Mint {
    static var presentYear = 2026
    private(set) var year: Int

    init() {
        year = Mint.presentYear
    }

    func update() {
        year = Mint.presentYear
    }

    func create(_ kind: Coin.Type) -> Coin {
        kind.init(year: year)
    }
}

class Coin {
    class var cents: Int { 0 }
    let year: Int

    required init(year: Int) {
        self.year = year
    }

    func worth() -> Int {
        type(of: self).cents + max(0, Mint.presentYear - year - 50)
    }
}

class Nickel: Coin {
    override class var cents: Int { 5 }
}

class Dime: Coin {
    override class var cents: Int { 10 }
}

let mint = Mint()
let dime = mint.create(Dime.self)
assert(dime.year == 2026 && dime.worth() == 10)
Mint.presentYear = 2126          // a century later
assert(dime.worth() == 60)       // 10 + (100 − 50)
mint.update()
let nickel = mint.create(Nickel.self)
assert(nickel.year == 2126 && nickel.worth() == 5)

class var is a type property that subclasses can override. Coin.Type is the type of the class itself, so mint.create(Dime.self) passes the class as a value; required init guarantees every subclass has that initializer.

Q5 (optional): A keyboard of buttons

A Button has a key and counts how many times it has been pressed; its press() returns the key. A Keyboard holds buttons numbered from 0, and has press(_:), which presses one button by number (returning "" for a number with no button), and typing(_:), which presses several and returns the text they produce.

Show solution
class Button {
    let key: String
    private(set) var pressed = 0

    init(key: String) {
        self.key = key
    }

    func press() -> String {
        pressed += 1
        return key
    }
}

class Keyboard {
    private var buttons: [Int: Button] = [:]

    init(_ buttons: [Button]) {
        for (index, button) in buttons.enumerated() {
            self.buttons[index] = button
        }
    }

    func press(_ number: Int) -> String {
        buttons[number]?.press() ?? ""
    }

    func typing(_ numbers: [Int]) -> String {
        numbers.map(press).joined()
    }
}

let h = Button(key: "H")
let i = Button(key: "I")
let keyboard = Keyboard([h, i])
assert(keyboard.typing([0, 1, 1, 7]) == "HII")
assert(i.pressed == 2)
assert(keyboard.press(0) == "H" && h.pressed == 2)

The keyboard and the test share the same button objects, so presses made through the keyboard are visible through h and i. That shared state is exactly what classes are for.

What’s next

Next lesson: protocols and generics, for code that works with many types at once.