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

References, identity, and memory

The start of the data structures half: boxes and arrows, the golden rule of assignment, parameter passing, identity versus equality, type members, and how ARC decides when an object dies.

CS61B
Intro to Java · Defining and Using Classes · Lists, Arrays, Maps, References · Textbook Ch. 1, Ch. 2, Ch. 3
Documentation
ObjectIdentifier · AnyObject

Units 1 to 3 followed CS61A: how to build abstractions from functions and data, and how a language runs them. This lesson starts the second half of the tutorial, which follows CS61B, Berkeley’s data structures course. The questions change. Instead of “how do I express this idea?”, they become “how is this collection actually stored, what does each operation cost, and how do I build one myself?”

CS61B begins by teaching Java to students who know Python. You already know Swift, so this lesson keeps the part of those first lectures that matters most for building data structures, and that trips up programmers in every language: what a variable actually holds.

Boxes and arrows

Think of every variable as a box. What goes in the box depends on the kind of type:

  • For a value type (Int, Double, Bool, String, arrays, dictionaries, and every struct and enum), the box holds the value itself.
  • For a reference type (every class), the box holds an arrow: a reference to an object that lives somewhere else in memory.

Here is the same idea as a structure and as a class. CS61B uses walruses for this example, and so will we:

struct WalrusValue {
    var weight: Int
}

final class Walrus {
    var weight: Int
    init(weight: Int) {
        self.weight = weight
    }
}

var a = WalrusValue(weight: 1000)
var b = a
b.weight = 5

let c = Walrus(weight: 1000)
let d = c
d.weight = 5

print(a.weight, c.weight)   // 1000 5

Drawn as boxes and arrows:

a ┌──────────────┐        c ┌───┐       ┌──────────────┐
  │ weight: 1000 │          │ ●─┼──────▶│ weight: 5    │
  └──────────────┘          └───┘   ┌──▶└──────────────┘
b ┌──────────────┐        d ┌───┐   │
  │ weight: 5    │          │ ●─┼───┘
  └──────────────┘          └───┘

a and b are two separate walruses. c and d are two arrows to one walrus, so a change made through d is seen through c. Note that c and d are let constants and the change still worked: let fixes the arrow, not the object it points to.

The golden rule of assignment

CS61B calls this the golden rule of equals, and it holds in Swift too:

b = a copies whatever is in a’s box into b’s box.

For a value type, that is the value. For a reference type, that is the arrow, so afterwards both boxes point at the same object. There is no special case to remember: assignment always copies the box. What differs is only what the box contains.

What would Swift print?

final class Counter {
    var count = 0
}
struct Tally {
    var count = 0
}
var x = Counter()
var y = x
y.count += 1
y = Counter()
y.count += 10
var p = Tally()
var q = p
q.count += 1
print(x.count, y.count, p.count, q.count)

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

Show answer and explanation

Answer1 10 0 1

y = x copies the arrow, so the first increment changes the counter x points to. y = Counter() then points y at a new counter; x is not affected, and still sees 1. The Tally values are independent from the start.

Passing arguments

Calling a function assigns each argument to its parameter, so the golden rule applies there too. A function receives a copy of the box:

final class Walrus {
    var weight: Int
    init(weight: Int) {
        self.weight = weight
    }
}

func feed(_ walrus: Walrus) {
    walrus.weight += 100        // follows the arrow: the caller sees this
}

func replace(_ walrus: Walrus) {
    var walrus = walrus         // a local copy of the arrow
    walrus = Walrus(weight: 0)  // points the copy elsewhere
    walrus.weight = 1
}

let w = Walrus(weight: 3500)
feed(w)
replace(w)
print(w.weight)   // 3600

feed follows the arrow and changes the shared walrus. replace only changes where its own copy of the arrow points, which the caller cannot see. To let a function change the caller’s box itself, Swift makes you say so with inout and &, as in Lesson 13. Nothing is ever passed “by reference” by accident.

Identity and equality

Two questions look alike but are different:

  • Equality, ==: do these two things have the same value? A type decides what that means by conforming to Equatable.
  • Identity, ===: are these two references arrows to the very same object? Only reference types have identity.
final class Walrus: Equatable {
    var weight: Int
    init(weight: Int) {
        self.weight = weight
    }
    static func == (lhs: Walrus, rhs: Walrus) -> Bool {
        lhs.weight == rhs.weight
    }
}

let a = Walrus(weight: 100)
let b = Walrus(weight: 100)
let c = a
print(a == b, a === b, a === c)   // true false true

a and b are equal but not identical: two walruses that happen to weigh the same. Java’s == is identity for objects, which is the source of one of CS61B’s most common bugs; in Swift, === makes identity a separate, visible question. ObjectIdentifier(a) turns an object’s identity into a Hashable value, which is how you put objects into a Set by identity rather than by value.

Type members

Everything above belongs to one instance: each walrus has its own weight. Properties and methods marked static belong to the type instead, and exist once however many instances there are. CS61B’s example is a dog class that knows its species’ scientific name and can compare two dogs:

struct Dog {
    static let binomen = "Canis familiaris"
    static private(set) var created = 0

    let name: String
    let size: Int

    init(name: String, size: Int) {
        self.name = name
        self.size = size
        Dog.created += 1
    }

    func noise() -> String {
        size < 10 ? "yip" : size < 30 ? "bark" : "woof"
    }

    static func larger(_ a: Dog, _ b: Dog) -> Dog {
        a.size >= b.size ? a : b
    }
}

let dogs = [Dog(name: "Maya", size: 5), Dog(name: "Rex", size: 40), Dog(name: "Kuma", size: 25)]
let biggest = dogs.reduce(dogs[0], Dog.larger)
print(Dog.binomen, Dog.created, biggest.name, biggest.noise())
// Canis familiaris 3 Rex woof

noise() is an instance method, because it depends on one dog’s size. larger needs no particular dog to call it on, so it is static, and is called on the type: Dog.larger. A static stored property like created is a single shared box, one of the few places where value types share state. Classes can also write class func or class var for type members that subclasses may override, as Ants did.

Arrays of objects

An array is a value type, but an array of objects holds arrows. That combination causes a classic bug:

What would Swift print?

final class Cell {
    var alive = false
}
var grid = [Cell](repeating: Cell(), count: 3)
grid[0].alive = true
print(grid.map(\.alive))
var fresh = (0..<3).map { _ in Cell() }
fresh[0].alive = true
print(fresh.map(\.alive))

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

Show answer and explanation

Answer[true, true, true] [true, false, false]

Cell() is evaluated once, and repeating: copies that arrow three times: one cell, three arrows. The map version calls Cell() once per element, making three cells. With a value type, both versions would give [true, false, false].

Copying an array of objects copies the arrows, not the objects. That is a shallow copy. When the elements must be independent too, a deep copy makes new objects: walruses.map { Walrus(weight: $0.weight) }.

Where objects live, and when they die

Every class instance takes memory, and something must decide when to give it back. Java uses a garbage collector, which periodically searches for objects nothing points to. Swift uses automatic reference counting (ARC): each object keeps a count of the strong references pointing at it, and the moment the count reaches zero, the object is destroyed. Just before that, its deinit runs:

final class Walrus {
    let name: String
    init(name: String) {
        self.name = name
        print("hello,", name)
    }
    deinit {
        print("goodbye,", name)
    }
}

var first: Walrus? = Walrus(name: "Wally")
var second = first      // two arrows: the count is 2
first = nil             // the count is 1
print("still here")
second = nil            // the count is 0: Wally is destroyed
print("done")
// hello, Wally
// still here
// goodbye, Wally
// done

The moment is predictable, which is useful: a deinit can close a file or release a lock exactly when the object is no longer needed. Swift promises that an object lives at least until the last place it is used, so do not rely on the exact line where a local variable’s object dies; setting an optional to nil, as above, is the reliable way to show it.

What would Swift print?

final class Node {
    let label: String
    var next: Node?
    init(_ label: String) {
        self.label = label
    }
    deinit {
        print("freed", label)
    }
}
var head: Node? = Node("a")
head!.next = Node("b")
head = nil
print("end")

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

Show answer and explanation

Answerfreed a freed b end

Setting head to nil drops the only reference to a, so a is freed. Freeing a releases its next arrow, the only reference to b, so b is freed right after. Freeing a linked structure frees everything reachable only through it, one step at a time.

Cycles

Reference counting has one weakness. If two objects point at each other, each keeps the other’s count above zero, and neither is ever freed, even after the rest of the program has forgotten them. That is a memory leak. Lesson 15 met this with weak; in counting terms:

  • A strong reference, the default, adds 1 to the count.
  • A weak reference does not count. It must be an optional var, and becomes nil automatically when its object is destroyed.
  • An unowned reference does not count either, and is not optional. Use it only when the object is guaranteed to outlive the reference; reading it after the object is gone crashes.
final class Person {
    let name: String
    var apartment: Apartment?
    init(name: String) { self.name = name }
    deinit { print(name, "freed") }
}

final class Apartment {
    let unit: String
    weak var tenant: Person?     // weak: the apartment does not own its tenant
    init(unit: String) { self.unit = unit }
    deinit { print(unit, "freed") }
}

var ada: Person? = Person(name: "Ada")
var flat: Apartment? = Apartment(unit: "4A")
ada!.apartment = flat
flat!.tenant = ada
ada = nil
flat = nil
// Ada freed
// 4A freed

Without weak, both deinits would stay silent: each object would hold the other alive forever. The rule of thumb is to decide which object owns which. Owners hold strong references; back-references, like a child’s link to its parent or a tenant’s apartment, are weak or unowned. Lesson 29’s doubly linked lists are built on exactly this decision.

Put the lines in order

Put the lines in order so the program prints 2 1.

  1. self.value = value
  2. let copy = Box(original.value)
  3. }
  4. let original = Box(1)
  5. print(original.value, copy.value)
  6. var value: Int
  7. let alias = original
  8. }
  9. init(_ value: Int) {
  10. alias.value = 2
  11. final class Box {

Show the correct program
final class Box {
    var value: Int
    init(_ value: Int) {
        self.value = value
    }
}
let original = Box(1)
let alias = original
let copy = Box(original.value)
alias.value = 2
print(original.value, copy.value)

Lab 24: References

Q0: What would Swift print?

What would Swift print?

final class Walrus {
    var weight: Int
    init(_ weight: Int) {
        self.weight = weight
    }
}
func swap(_ a: Walrus, _ b: Walrus) {
    let temp = a.weight
    a.weight = b.weight
    b.weight = temp
}
let x = Walrus(1)
let y = Walrus(2)
swap(x, y)
swap(x, x)
print(x.weight, y.weight)

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

Show answer and explanation

Answer2 1

The first call follows both arrows and exchanges the weights. The second passes the same walrus twice: temp is 2, and both assignments write 2 to the one walrus, so nothing changes.

What would Swift print?

var scores = ["ada": [1, 2]]
var copy = scores
copy["ada"]!.append(3)
scores["ada"]![0] = 10
print(scores["ada"]!, copy["ada"]!)

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

Show answer and explanation

Answer[10, 2] [1, 2, 3]

A dictionary of arrays is values all the way down. copy is independent, and changing an element through scores["ada"]! changes the array inside the dictionary in place.

Q1: Boxes and arrows

Draw the boxes and arrows after this code runs, then predict what it prints.

final class Node {
    var value: Int
    var next: Node?
    init(_ value: Int, _ next: Node? = nil) {
        self.value = value
        self.next = next
    }
}

let c = Node(3)
let b = Node(2, c)
let a = Node(1, b)
let d = a.next
d!.value = 20
a.next = c
print(a.value, a.next!.value, b.value, d === b)
Show solution

It prints 1 3 20 true.

a ──▶ [1 | ●]──┐            (a.next now skips b)
               ▼
d ──▶ [20 | ●]──▶ [3 | nil] ◀── c
      ▲
b ────┘

d = a.next copies the arrow to the node that b also points to, so d!.value = 20 changes b’s node. Then a.next = c redirects a’s arrow to the last node. b’s node still exists, because b and d point to it, and it still points to c’s node.

Q2: Dogs

Extend Dog with a static method largest(_:) that returns the largest dog in an array (or nil for an empty array), and an instance method isLarger(than:). Keep a static count of how many dogs have been created, and check it.

Show solution
struct Dog {
    static private(set) var created = 0

    let name: String
    let size: Int

    init(name: String, size: Int) {
        self.name = name
        self.size = size
        Dog.created += 1
    }

    func isLarger(than other: Dog) -> Bool {
        size > other.size
    }

    static func largest(_ dogs: [Dog]) -> Dog? {
        dogs.max { $1.isLarger(than: $0) }
    }
}

let pack = [Dog(name: "Maya", size: 5), Dog(name: "Rex", size: 40), Dog(name: "Kuma", size: 25)]
assert(Dog.largest(pack)?.name == "Rex")
assert(Dog.largest([]) == nil)
assert(pack[2].isLarger(than: pack[0]))
assert(Dog.created == 3)

max(by:) takes an “is less than” function, so it is given “the second is larger than the first”. Reusing isLarger(than:) keeps the comparison in one place. Copying a Dog value does not call init, so created counts dogs created, not copies.

Q3: Deep copies

A Pack of walruses is a class holding an array of Walrus objects. Write shallowCopy() and deepCopy(), and show the difference with a test.

Show solution
final class Walrus {
    var weight: Int
    init(weight: Int) {
        self.weight = weight
    }
}

final class Pack {
    var members: [Walrus]
    init(_ members: [Walrus]) {
        self.members = members
    }

    func shallowCopy() -> Pack {
        Pack(members)
    }

    func deepCopy() -> Pack {
        Pack(members.map { Walrus(weight: $0.weight) })
    }
}

let pack = Pack([Walrus(weight: 100), Walrus(weight: 200)])
let shallow = pack.shallowCopy()
let deep = pack.deepCopy()
pack.members[0].weight = 999
pack.members.append(Walrus(weight: 1))

assert(shallow.members.map(\.weight) == [999, 200])   // shares the walruses
assert(deep.members.map(\.weight) == [100, 200])      // its own walruses
assert(shallow.members.count == 2)                    // but its own array

The shallow copy has its own array, since arrays are values, so the new walrus appended to pack does not appear in it. The arrows inside it still lead to the original walruses.

Q4: Counting live objects

Write a class Tracked that keeps a static count of how many instances are currently alive: increase it in init, decrease it in deinit. Use it to show that a two-object cycle leaks, and that making one reference weak fixes it.

Show solution
final class Tracked {
    static private(set) var alive = 0
    var next: Tracked?
    weak var back: Tracked?

    init() {
        Tracked.alive += 1
    }

    deinit {
        Tracked.alive -= 1
    }
}

var a: Tracked? = Tracked()
var b: Tracked? = Tracked()
a!.next = b
b!.next = a        // a cycle of strong references
a = nil
b = nil
assert(Tracked.alive == 2)   // leaked: nothing can reach them, and they are never freed

var c: Tracked? = Tracked()
var d: Tracked? = Tracked()
c!.next = d
d!.back = c          // the back-reference does not count
c = nil
d = nil
assert(Tracked.alive == 2)   // only the two leaked objects remain

After the first part, the program has no way to reach the two leaked objects, and ARC will never free them. The second pair is freed as soon as the variables are cleared: c has no strong references once c is nil, and freeing it releases the only strong reference to d.

Q5: Unique by identity

Write uniqueObjects(_:), which removes repeated references from an array of Walrus objects, keeping the first occurrence of each object, even when different objects are equal in weight. Use ObjectIdentifier.

Show solution
final class Walrus {
    var weight: Int
    init(weight: Int) {
        self.weight = weight
    }
}

func uniqueObjects(_ walruses: [Walrus]) -> [Walrus] {
    var seen: Set<ObjectIdentifier> = []
    return walruses.filter { seen.insert(ObjectIdentifier($0)).inserted }
}

let a = Walrus(weight: 100)
let b = Walrus(weight: 100)
let result = uniqueObjects([a, b, a, a, b])
assert(result.count == 2)
assert(result[0] === a && result[1] === b)

Set.insert returns whether the element was new, so the filter keeps exactly the first occurrence of each identity. a and b weigh the same but are different objects, so both are kept.

Q6 (optional): A shared bank, and a private one

Write a class SharedAccount and a structure PrivateAccount, each with a balance and a deposit(_:) method. Write one generic function depositTwice(_:) that works for both through a protocol, and explain why it needs inout for the structure but not for the class.

Show solution
protocol Account {
    var balance: Int { get }
    mutating func deposit(_ amount: Int)
}

final class SharedAccount: Account {
    private(set) var balance = 0
    func deposit(_ amount: Int) {
        balance += amount
    }
}

struct PrivateAccount: Account {
    private(set) var balance = 0
    mutating func deposit(_ amount: Int) {
        balance += amount
    }
}

func depositTwice<A: Account>(_ account: inout A) {
    account.deposit(10)
    account.deposit(10)
}

var shared = SharedAccount()
let alias = shared
depositTwice(&shared)
assert(alias.balance == 20)       // the same object

var mine = PrivateAccount()
let snapshot = mine
depositTwice(&mine)
assert(mine.balance == 20 && snapshot.balance == 0)

A mutating requirement lets a structure change itself, so a generic function has to take the value inout to change the caller’s copy. A class satisfies the requirement with an ordinary method, since changing an object never changes the arrow to it. Generic code written against the protocol works for both kinds of type, but the difference in what = copies still shows through: alias sees the deposits, snapshot does not.

What’s next

The CS61B projects draw on screen, and the first one is a falling-sand physics sandbox. Next lesson: drawing with SwiftUI.