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

Iteration, equality, and ordering

Making your own collection feel built in: an ArraySet with for–in through Sequence and Collection, a description, equality that matches its meaning, hashing that agrees with equality, Comparable, comparator functions, and operators.

CS61B
Iterators, Iterables, and Equals · Comparables and Comparators · Textbook Ch. 9, Ch. 10

The lists we have built work, but they feel foreign next to Swift’s own types. You cannot loop over them with for–in, compare them with ==, print them readably, or sort them. Swift’s own collections get all of that from a handful of standard protocols, and so can yours. CS61B covers the Java equivalents (Iterable, equals, hashCode, toString, Comparable, Comparator) with an ArraySet, and we will build the same set.

An ArraySet

A set holds each item at most once. Stored in an array, add checks for the item first, so it takes linear time; Lessons 38 and 48 make sets fast. The point here is the protocols, so simple is fine:

struct ArraySet<Element: Equatable> {
    private var items: [Element] = []

    var count: Int { items.count }

    func contains(_ item: Element) -> Bool {
        items.contains(item)
    }

    mutating func add(_ item: Element) {
        if !contains(item) {
            items.append(item)
        }
    }
}

Element: Equatable is a constraint: contains needs == to compare items, so the set only accepts element types that have it.

Iteration

A for–in loop works with any type that conforms to Sequence. Swift turns

for item in set {
    print(item)
}

into calls on an iterator:

var iterator = set.makeIterator()
while let item = iterator.next() {
    print(item)
}

So a sequence needs one method, makeIterator(), returning a value that conforms to IteratorProtocol, whose next() returns each item and then nil. Lesson 17 made types that were their own iterators; for a collection, the iterator is a separate small type, so that two loops over the same set do not interfere:

struct ArraySet<Element: Equatable> {
    private var items: [Element] = []
    var count: Int { items.count }
    func contains(_ item: Element) -> Bool { items.contains(item) }
    mutating func add(_ item: Element) {
        if !contains(item) {
            items.append(item)
        }
    }
}

extension ArraySet: Sequence {
    struct Iterator: IteratorProtocol {
        fileprivate let items: [Element]
        fileprivate var position = 0

        mutating func next() -> Element? {
            guard position < items.count else {
                return nil
            }
            defer { position += 1 }
            return items[position]
        }
    }

    func makeIterator() -> Iterator {
        Iterator(items: items)
    }
}

var set = ArraySet<String>()
for word in ["to", "be", "or", "not", "to", "be"] {
    set.add(word)
}
for word in set {
    print(word, terminator: " ")
}
print()
print(set.map { $0.uppercased() }, set.contains("or"), set.min()!)
// to be or not
// ["TO", "BE", "OR", "NOT"] true be

Conforming to Sequence does much more than enable for–in. Every method that Sequence defines in its protocol extensions now works on ArraySet: map, filter, reduce, contains(where:), first(where:), sorted(), min() for comparable elements, enumerated(), zip, and dozens more. Eight lines of conformance buy the whole vocabulary of Lesson 9.

Collection

A Sequence can only be walked from the start, possibly once. A Collection promises more: it can be walked many times, and every item has an index that leads straight back to it. A conformance needs a start index, an end index (one past the last item), a way to step from one index to the next, and a subscript:

extension ArraySet: Collection {
    var startIndex: Int { 0 }
    var endIndex: Int { count }
    func index(after i: Int) -> Int { i + 1 }
    subscript(position: Int) -> Element { items[position] }
}

In return, the set gets first, isEmpty, indices, firstIndex(of:), slicing with ranges, and a count that works for any collection. An Iterator comes free too, so a type that is a Collection does not even need the iterator written above. Conforming to BidirectionalCollection adds last and reversed(); RandomAccessCollection promises that jumping between indices takes constant time, which makes count and distances fast. Lab Q2 gives Lesson 30’s AList all of these.

What would Swift print?

struct Countdown: Sequence, IteratorProtocol {
    var n: Int
    mutating func next() -> Int? {
        guard n > 0 else { return nil }
        defer { n -= 1 }
        return n
    }
}
let c = Countdown(n: 3)
print(Array(c), Array(c), c.reduce(0, +))

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

Show answer and explanation

Answer[3, 2, 1] [3, 2, 1] 6

A value type that is its own iterator is copied each time a loop starts, so each use counts down from 3 again. A class used the same way would be used up after the first loop, which is one reason collections keep their iterator separate.

A readable description

print(set) would currently show the structure’s internals. Conforming to CustomStringConvertible with a description property decides what printing shows, like Java’s toString:

extension ArraySet: CustomStringConvertible {
    var description: String {
        "{" + map { "\($0)" }.joined(separator: ", ") + "}"
    }
}

String interpolation and print both use description. A related protocol, CustomDebugStringConvertible, controls what debuggers and debugPrint show.

Equality

== asks whether two values are the same in meaning. For a structure whose properties are all Equatable, Swift can write it for you: declare the conformance, and two values are equal when all their stored properties are. That is right for most types, but not for a set:

struct ArraySet<Element: Equatable>: Equatable {
    private var items: [Element] = []
    mutating func add(_ item: Element) {
        if !items.contains(item) {
            items.append(item)
        }
    }
}

var a = ArraySet<Int>()
var b = ArraySet<Int>()
a.add(1); a.add(2)
b.add(2); b.add(1)
print(a == b)   // false

The synthesized == compares the arrays, which have the same items in a different order. As sets, {1, 2} and {2, 1} are equal, so the set must say what equality means:

extension ArraySet: Equatable {
    static func == (lhs: ArraySet, rhs: ArraySet) -> Bool {
        lhs.count == rhs.count && lhs.allSatisfy { rhs.contains($0) }
    }
}

Equality must behave like equality, or code that depends on it breaks in confusing ways. Every == must be reflexive (a == a), symmetric (if a == b then b == a), and transitive (if a == b and b == c, then a == c). The count check is what makes this one symmetric: without it, {1} would equal {1, 2} but not the other way round.

Java’s == compares references and .equals compares meaning, a distinction that causes endless CS61B bugs. Swift’s == is always meaning, and identity has its own operator, ===, as Lesson 25 showed.

Hashing agrees with equality

Set and Dictionary find items by their hash, a number computed from the value, and only then compare with ==. Lesson 48 explains how. What matters now is the one rule a Hashable type must follow, the same rule as Java’s hashCode:

If a == b, then a and b must have the same hash.

A synthesized Hashable conformance hashes all the stored properties, which agrees with a synthesized ==. But a custom == needs a matching custom hash(into:). For our set, equality ignores order, so the hash must too:

extension ArraySet: Hashable where Element: Hashable {
    func hash(into hasher: inout Hasher) {
        hasher.combine(count)
        hasher.combine(items.map(\.hashValue).reduce(0, &+))   // order does not matter
    }
}

Adding the elements’ hash values gives the same total in any order. (&+ adds and wraps around on overflow instead of crashing, one of the Swift book’s advanced operators.) where Element: Hashable makes the set hashable only when its elements are, a conditional conformance.

Break the rule, and a Set of these values can hold two equal items, or fail to find one that is there. Lab Q4 shows it happening.

Ordering

Comparable gives a type a natural order: implement <, and Swift derives >, <=, and >=, and makes sorted(), min(), max(), and ranges available:

struct Dog: Comparable, CustomStringConvertible {
    let name: String
    let size: Int

    static func < (lhs: Dog, rhs: Dog) -> Bool {
        lhs.size < rhs.size
    }

    var description: String { name }
}

let dogs = [Dog(name: "Rex", size: 40), Dog(name: "Maya", size: 5), Dog(name: "Kuma", size: 25)]
print(dogs.max()!, dogs.sorted(), dogs.sorted(by: >))   // Rex [Maya, Kuma, Rex] [Rex, Kuma, Maya]

This is one of Swift’s operator methods: a static func whose name is an operator. Any operator can be given meaning for your type the same way, including + and ==. Enums without associated values can even get Comparable synthesized, ordered by their cases.

A comparison must also behave: if a < b and b < c, then a < c, and never both a < b and b < a. sort relies on it and may produce nonsense, or worse, if it does not hold.

Comparators

A type has at most one natural order, but a program may need many: dogs by size for one screen, by name for another. CS61B passes a Comparator object. In Swift, a comparator is usually just a function (Dog, Dog) -> Bool that says whether the first comes before the second:

let byName = dogs.sorted { $0.name < $1.name }            // [Kuma, Maya, Rex]
let longestName = dogs.max { $0.name.count < $1.name.count }

Foundation adds SortComparator types for more structured cases, such as sorting by a key path, in a chosen direction, with ties broken by a second key:

import Foundation

struct Dog {
    let name: String
    let size: Int
}

let dogs = [Dog(name: "Rex", size: 25), Dog(name: "Maya", size: 5), Dog(name: "Kuma", size: 25)]
let ordered = dogs.sorted(using: [
    KeyPathComparator(\.size, order: .reverse),
    KeyPathComparator(\.name),
])
print(ordered.map(\.name))   // ["Kuma", "Rex", "Maya"]

The first comparator orders by size, largest first; the second decides between the two dogs of size 25.

Put the lines in order

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

  1. struct Pair: Comparable {
  2. static func < (lhs: Pair, rhs: Pair) -> Bool {
  3. let pairs = [Pair(a: 1), Pair(a: 2)]
  4. lhs.a > rhs.a
  5. let a: Int
  6. print(pairs.min()!.a, pairs.max()!.a)
  7. }
  8. }

Show the correct program
struct Pair: Comparable {
    let a: Int
    static func < (lhs: Pair, rhs: Pair) -> Bool {
        lhs.a > rhs.a
    }
}
let pairs = [Pair(a: 1), Pair(a: 2)]
print(pairs.min()!.a, pairs.max()!.a)

Lab 31: Iteration and equality

Q0: What would Swift print?

What would Swift print?

struct Point: Hashable {
    var x: Int
    var y: Int
}
let points: Set = [Point(x: 1, y: 2), Point(x: 1, y: 2), Point(x: 2, y: 1)]
print(points.count, Point(x: 1, y: 2) == Point(x: 2, y: 1))

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

Show answer and explanation

Answer2 false

The synthesized conformances compare and hash both properties, so the two equal points are one element of the set, and (1, 2) differs from (2, 1).

What would Swift print?

enum Size: Comparable {
    case small, medium, large
}
let sizes: [Size] = [.large, .small, .medium]
print(sizes.sorted() == [.small, .medium, .large], sizes.max() == .large)

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

Show answer and explanation

Answertrue true

For an enum without associated values, a Comparable conformance is synthesized, ordering the cases as they are declared.

Q1: A complete ArraySet

Put the pieces of this lesson together: an ArraySet that is a Collection, CustomStringConvertible, Equatable with order-independent equality, and Hashable when its elements are. Test that equal sets built in different orders are equal, hash equally, and count as one element in a Set.

Show solution
struct ArraySet<Element: Equatable> {
    private var items: [Element] = []

    init() {}

    init(_ elements: some Sequence<Element>) {
        for element in elements {
            add(element)
        }
    }

    mutating func add(_ item: Element) {
        if !items.contains(item) {
            items.append(item)
        }
    }
}

extension ArraySet: Collection {
    var startIndex: Int { 0 }
    var endIndex: Int { items.count }
    func index(after i: Int) -> Int { i + 1 }
    subscript(position: Int) -> Element { items[position] }
}

extension ArraySet: CustomStringConvertible {
    var description: String {
        "{" + map { "\($0)" }.joined(separator: ", ") + "}"
    }
}

extension ArraySet: Equatable {
    static func == (lhs: ArraySet, rhs: ArraySet) -> Bool {
        lhs.count == rhs.count && lhs.allSatisfy { rhs.items.contains($0) }
    }
}

extension ArraySet: Hashable where Element: Hashable {
    func hash(into hasher: inout Hasher) {
        hasher.combine(count)
        hasher.combine(items.map(\.hashValue).reduce(0, &+))
    }
}

let a = ArraySet([1, 2, 3, 2])
let b = ArraySet([3, 1, 2])
assert(a.description == "{1, 2, 3}")
assert(a == b && a.hashValue == b.hashValue)
assert(Set([a, b]).count == 1)
assert(a != ArraySet([1, 2]) && ArraySet([1, 2]) != a)
assert(a.first == 1 && a.contains(3) && a.count == 3)

Collection supplies count, first, and contains, so the set no longer needs its own. The last line of tests checks symmetry in both directions, which is the property the count check exists for.

Q2: AList becomes a real collection

Take Lesson 30’s AList and make it a RandomAccessCollection and a MutableCollection. Then, without writing any more code, use sort(), reverse(), firstIndex(of:), and last on it.

Show solution
struct AList<Element> {
    private var items = [Element?](repeating: nil, count: 8)
    private(set) var count = 0

    mutating func addLast(_ item: Element) {
        if count == items.count {
            var bigger = [Element?](repeating: nil, count: items.count * 2)
            for i in 0..<count {
                bigger[i] = items[i]
            }
            items = bigger
        }
        items[count] = item
        count += 1
    }
}

extension AList: RandomAccessCollection, MutableCollection {
    var startIndex: Int { 0 }
    var endIndex: Int { count }

    subscript(position: Int) -> Element {
        get {
            precondition(indices.contains(position))
            return items[position]!
        }
        set {
            precondition(indices.contains(position))
            items[position] = newValue
        }
    }
}

var list = AList<Int>()
for n in [5, 3, 9, 1, 7, 2, 8, 6, 4] {
    list.addLast(n)
}
list.sort()
assert(Array(list) == Array(1...9))
list.reverse()
assert(list.first == 9 && list.last == 1)
assert(list.firstIndex(of: 7) == 2)
assert(list[2...4].reduce(0, +) == 7 + 6 + 5)

With Int indices, RandomAccessCollection fills in index(after:), index(before:), and distances automatically. MutableCollection needs only the settable subscript, and in return provides the in-place sort(), reverse(), swapAt, and partition. The slice list[2...4] shares the list’s storage.

Q3: Dogs, many ways

Using the lesson’s Dog, write expressions for: the dogs sorted by name; the largest dog whose name starts with a given letter; and the dogs sorted by size with ties in size broken by name, first as a single closure and then with KeyPathComparator.

Show solution
import Foundation

struct Dog: Comparable {
    let name: String
    let size: Int

    static func < (lhs: Dog, rhs: Dog) -> Bool {
        lhs.size < rhs.size
    }
}

let dogs = [Dog(name: "Rex", size: 25), Dog(name: "Maya", size: 5),
            Dog(name: "Kuma", size: 25), Dog(name: "Rufus", size: 30)]

let byName = dogs.sorted { $0.name < $1.name }
let largestR = dogs.filter { $0.name.hasPrefix("R") }.max()
let bySizeThenName = dogs.sorted { ($0.size, $0.name) < ($1.size, $1.name) }
let withComparators = dogs.sorted(using: [KeyPathComparator(\.size), KeyPathComparator(\.name)])

assert(byName.map(\.name) == ["Kuma", "Maya", "Rex", "Rufus"])
assert(largestR?.name == "Rufus")
assert(bySizeThenName.map(\.name) == ["Maya", "Kuma", "Rex", "Rufus"])
assert(withComparators.map(\.name) == bySizeThenName.map(\.name))

Tuples of comparable values compare element by element, so (size, name) < (size, name) is a compact way to break ties. max() uses the natural order, by size.

Q4: When hashing disagrees

Write a Word type whose == ignores case, first with the synthesized Hashable, and show that a Set<Word> can then contain two equal words. Then fix it with a hash(into:) that agrees with ==.

Show solution
struct BrokenWord: Hashable {
    let text: String
    static func == (lhs: BrokenWord, rhs: BrokenWord) -> Bool {
        lhs.text.lowercased() == rhs.text.lowercased()
    }
    // hash(into:) is synthesized from `text`, which does not ignore case
}

struct Word: Hashable {
    let text: String
    static func == (lhs: Word, rhs: Word) -> Bool {
        lhs.text.lowercased() == rhs.text.lowercased()
    }
    func hash(into hasher: inout Hasher) {
        hasher.combine(text.lowercased())
    }
}

// Every capitalization of "swift": 32 words, all equal to each other.
let spellings = (0..<32).map { mask in
    String("swift".enumerated().map { i, c in mask & (1 << i) != 0 ? Character(c.uppercased()) : c })
}
assert(BrokenWord(text: "Swift") == BrokenWord(text: "swift"))
assert(BrokenWord(text: "Swift").hashValue != BrokenWord(text: "swift").hashValue)
let broken = Set(spellings.map(BrokenWord.init))
assert(broken.count > 1)    // a set of equal words, with several elements

let fixed = Set(spellings.map(Word.init))
assert(fixed.count == 1)
assert(fixed.contains(Word(text: "sWiFt")))

With the synthesized hash, equal words hash differently, so they usually land in different places and the set never compares them: the “set” ends up with many elements that are all equal. How many varies from run to run, because Swift seeds its hashing randomly each time a program starts, which makes this bug inconsistent as well as wrong. Hashing the same lowercased text that == compares makes the two agree, and all 32 spellings become one element.

Q5: Walking a linked list

Make Lesson 29’s LinkedListDeque a Sequence, with an iterator that holds a reference to the current node and stops when it comes back to the sentinel. Then use Array(deque), deque.reduce, and zip on it.

Show solution
final class LinkedListDeque<Element> {
    fileprivate final class Node {
        var item: Element?
        var next: Node!
        weak var prev: Node!
        init(_ item: Element?) { self.item = item }
    }

    fileprivate let sentinel = Node(nil)
    private(set) var count = 0

    init() {
        sentinel.next = sentinel
        sentinel.prev = sentinel
    }

    deinit {
        sentinel.next = nil
    }

    func addLast(_ item: Element) {
        let new = Node(item)
        new.prev = sentinel.prev
        new.next = sentinel
        sentinel.prev.next = new
        sentinel.prev = new
        count += 1
    }
}

extension LinkedListDeque: Sequence {
    struct Iterator: IteratorProtocol {
        fileprivate let sentinel: Node
        fileprivate var current: Node

        mutating func next() -> Element? {
            guard current !== sentinel else {
                return nil
            }
            defer { current = current.next }
            return current.item
        }
    }

    func makeIterator() -> Iterator {
        Iterator(sentinel: sentinel, current: sentinel.next)
    }
}

let deque = LinkedListDeque<Int>()
for n in 1...4 {
    deque.addLast(n * n)
}
assert(Array(deque) == [1, 4, 9, 16])
assert(deque.reduce(0, +) == 30)
assert(zip(deque, deque.dropFirst()).map { $1 - $0 } == [3, 5, 7])

The nested types use fileprivate rather than private so that the iterator, declared in an extension in the same file, can see them. The iterator holds the sentinel strongly while it runs, which keeps the ring alive even if the deque itself were freed during the loop.

Q6 (optional): A union operator

Give ArraySet two operators: + for union and & for intersection. Then declare a new operator, ∈, for membership, so that 2 ∈ set reads like mathematics. The Swift book’s chapter on advanced operators explains how to declare one.

Show solution
struct ArraySet<Element: Equatable> {
    private(set) var items: [Element] = []

    init(_ elements: [Element] = []) {
        for element in elements where !items.contains(element) {
            items.append(element)
        }
    }

    static func + (lhs: ArraySet, rhs: ArraySet) -> ArraySet {
        ArraySet(lhs.items + rhs.items)
    }

    static func & (lhs: ArraySet, rhs: ArraySet) -> ArraySet {
        ArraySet(lhs.items.filter { rhs.items.contains($0) })
    }
}

infix operator ∈: ComparisonPrecedence

func ∈ <Element>(item: Element, set: ArraySet<Element>) -> Bool {
    set.items.contains(item)
}

let odds = ArraySet([1, 3, 5, 7])
let primes = ArraySet([2, 3, 5, 7])
assert((odds + primes).items == [1, 3, 5, 7, 2])
assert((odds & primes).items == [3, 5, 7])
assert(3 ∈ odds && !(2 ∈ odds))

infix operator ∈: ComparisonPrecedence declares the operator and gives it the same precedence as == and <, so 3 ∈ odds && … groups the way it reads. New operators are powerful and easy to overuse: use one only where the symbol is already standard in the field, as ∈ is in mathematics.

What’s next

Our collections are classes or use arrays of optionals. Next lesson: how Swift’s Array manages to be a value type without copying everything, and how to give your own collections the same behavior.