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

Protocols and generics

Interfaces in Swift: protocols that name what a type can do, default implementations in extensions, the standard protocols behind printing and comparing, and generic functions and types.

CS61A
Object Examples (interfaces) · Composing Programs 2.7
Documentation
Equatable · Comparable · Hashable

CS61A describes an interface as a set of shared messages: if several kinds of object all respond to area, code can ask any of them for its area without knowing which kind it has. Python relies on convention for this. Swift writes the interface down as a protocol, and the compiler checks that every type claiming to follow it really does.

Protocols

A protocol lists requirements: properties and methods a conforming type must provide.

protocol Shape {
    var name: String { get }
    var area: Double { get }
}

struct Square: Shape {
    var side: Double
    var name: String { "square" }
    var area: Double { side * side }
}

struct Circle: Shape {
    var radius: Double
    var name: String { "circle" }
    var area: Double { Double.pi * radius * radius }
}

let shapes: [any Shape] = [Square(side: 2), Circle(radius: 1)]
for shape in shapes {
    print(shape.name, shape.area)
}

{ get } means the property must be readable; a stored or computed property both satisfy it. [any Shape] is an array whose elements can be any type that conforms to Shape. If Circle forgot area, the program would not compile.

Default implementations

An extension adds methods to an existing type, including a protocol. Methods added to a protocol extension are available to every conforming type:

protocol Animal {
    var name: String { get }
    func sound() -> String
}

extension Animal {
    func speak() -> String {
        "\(name) says \(sound())"
    }
}

struct Dog: Animal {
    let name: String
    func sound() -> String { "woof" }
}

print(Dog(name: "Rex").speak())   // Rex says woof

Dog only had to supply name and sound; speak came for free. This is how Swift shares behavior without inheritance, and it works for structures and enumerations as well as classes.

What would Swift print?

protocol Animal {
    var name: String { get }
    func sound() -> String
}
extension Animal {
    func speak() -> String { "\(name) says \(sound())" }
}
struct Cat: Animal {
    let name: String
    func sound() -> String { "meow" }
}
struct Cow: Animal {
    let name: String
    func sound() -> String { "moo" }
}
let animals: [any Animal] = [Cat(name: "Tom"), Cow(name: "Bess")]
print(animals.map { $0.speak() })

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

Show answer and explanation

Answer["Tom says meow", "Bess says moo"]

Each element uses its own name and sound, and the shared speak from the extension puts them together. map collects the two strings into an array.

Extensions work on types you did not write, too:

extension Int {
    var isEven: Bool { self % 2 == 0 }
}
print(4.isEven, 7.isEven)   // true false

The standard protocols

Much of what you have used so far is protocols from the standard library.

  • CustomStringConvertible: a description property that print uses.
  • Equatable: ==. For a structure whose properties are all equatable, Swift writes == for you.
  • Comparable: <, which also gives sorted(), max(), and friends.
  • Hashable: needed to be a dictionary key or set element; also synthesized for simple structures.
struct Money: CustomStringConvertible, Comparable, Hashable {
    let cents: Int

    var description: String {
        let remainder = cents % 100
        return "$\(cents / 100)." + (remainder < 10 ? "0" : "") + String(remainder)
    }

    static func < (a: Money, b: Money) -> Bool {
        a.cents < b.cents
    }
}

print(Money(cents: 1234))                                // $12.34
print([Money(cents: 300), Money(cents: 100)].sorted())   // [$1.00, $3.00]
print(Money(cents: 5) == Money(cents: 5))                // true

static func < defines the operator for this type; == and hashing were generated because cents is an Int.

What would Swift print?

struct Point: Equatable {
    var x: Int
    var y: Int
}
let a = Point(x: 1, y: 2)
print(a == Point(x: 1, y: 2), a == 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

Answertrue false

Declaring Equatable is enough: Swift compares the properties one by one. The second point has the same numbers in a different order, so it is not equal.

Generics

A generic function works for any type that meets some requirement, written as a type parameter in angle brackets:

func largest<T: Comparable>(_ values: [T]) -> T? {
    guard var best = values.first else {
        return nil
    }
    for value in values where value > best {
        best = value
    }
    return best
}

print(largest([3, 9, 2]) ?? 0)            // 9
print(largest(["pear", "apple"]) ?? "")   // pear

T: Comparable says: T can be any type, as long as it conforms to Comparable, which is exactly what > needs. One definition serves integers, strings, and Money, and Swift still checks types: a call on an array of shapes would not compile, because shapes cannot be compared.

Types can be generic too. Array<Int> is the full name of [Int]. Here is a stack that holds any element type:

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

    var isEmpty: Bool { items.isEmpty }

    mutating func push(_ item: Element) {
        items.append(item)
    }

    mutating func pop() -> Element? {
        items.popLast()
    }
}

var stack = Stack<String>()
stack.push("a")
stack.push("b")
print(stack.pop()!, stack.pop()!, stack.isEmpty)   // b a true

Constraints with where

A where clause adds requirements to a generic function’s type parameters, including requirements on associated types such as a sequence’s Element:

func total<S: Sequence>(_ values: S) -> S.Element where S.Element: Numeric {
    values.reduce(0, +)
}
print(total([1, 2, 3]), total([1.5, 2.5]), total(1...4))   // 6 4.0 10

Numeric is the standard protocol for types that support + and *, so one function adds up integers, doubles, and ranges.

Protocols with associated types

A protocol can leave one of its types for each conforming type to choose. associatedtype Item means “some type, decided by whoever conforms”:

protocol Container {
    associatedtype Item
    var items: [Item] { get }
}

extension Container {
    var count: Int { items.count }
}

struct Bag: Container {
    var items: [String]   // Item is String here
}
print(Bag(items: ["a", "b"]).count)   // 2

Sequence itself works this way: its Element is an associated type.

Put the lines in order

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

  1. print(count([1, 2, 3, 4], where: { $0 > 2 }), count("banana", where: { $0 == "a" }))
  2. func count<S: Sequence>(_ items: S, where test: (S.Element) -> Bool) -> Int {
  3. total += 1
  4. var total = 0
  5. return total
  6. }
  7. for item in items where test(item) {
  8. }

Show the correct program
func count<S: Sequence>(_ items: S, where test: (S.Element) -> Bool) -> Int {
    var total = 0
    for item in items where test(item) {
        total += 1
    }
    return total
}
print(count([1, 2, 3, 4], where: { $0 > 2 }), count("banana", where: { $0 == "a" }))

Sequence is the protocol behind every for-in loop, and S.Element is whatever type it yields: Int for the array, Character for the string. Lesson 9’s “sequence abstraction” is this protocol.

Lab 15: Interfaces

Q0: What would Swift print?

What would Swift print?

protocol Greeter {
    func greet() -> String
}
extension Greeter {
    func greet() -> String { "hello" }
}
struct Plain: Greeter {}
struct Loud: Greeter {
    func greet() -> String { "HELLO" }
}
print(Plain().greet(), Loud().greet())

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

Show answer and explanation

Answerhello HELLO

Plain uses the default from the extension; Loud provides its own, which takes priority.

What would Swift print?

func firstOrDefault<T>(_ values: [T], _ fallback: T) -> T {
    values.first ?? fallback
}
print(firstOrDefault([3, 4], 0), firstOrDefault([String](), "none"))

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

Show answer and explanation

Answer3 none

T is Int in the first call and String in the second. An empty array has no first element, so the fallback is used.

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)

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

Show answer and explanation

Answer2

Hashable is synthesized from the properties, so the two equal points count once in the set.

Q1: A generic queue

Write Queue<Element>, a structure with enqueue(_:), dequeue() (returning an optional, first in first out), and a count property.

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

    var count: Int { items.count }

    mutating func enqueue(_ item: Element) {
        items.append(item)
    }

    mutating func dequeue() -> Element? {
        items.isEmpty ? nil : items.removeFirst()
    }
}

var queue = Queue<Int>()
queue.enqueue(1)
queue.enqueue(2)
assert(queue.count == 2)
assert(queue.dequeue() == 1)
assert(queue.dequeue() == 2)
assert(queue.dequeue() == nil)

removeFirst() shifts every remaining element, so this queue gets slow when large. Lesson 18 discusses measuring that; a faster queue keeps two stacks.

Q2: Describable shapes

Make Square and Circle from this lesson conform to CustomStringConvertible with a single extension on the Shape protocol, so that print(Square(side: 2)) prints square (area 4.0).

Show solution
protocol Shape: CustomStringConvertible {
    var name: String { get }
    var area: Double { get }
}

extension Shape {
    var description: String { "\(name) (area \(area))" }
}

struct Square: Shape {
    var side: Double
    var name: String { "square" }
    var area: Double { side * side }
}

print(Square(side: 2))
assert(Square(side: 2).description == "square (area 4.0)")

protocol Shape: CustomStringConvertible makes every shape describable, and the extension supplies description for all of them at once.

Q3: Smallest by a key

Write a generic function smallest(_:by:) that returns the element for which a key function gives the smallest value, or nil for an empty array. For example, the shortest word in an array of strings.

func smallest<T, Key: Comparable>(_ items: [T], by key: (T) -> Key) -> T? {
    // your code here
}
Show solution
func smallest<T, Key: Comparable>(_ items: [T], by key: (T) -> Key) -> T? {
    guard var best = items.first else {
        return nil
    }
    for item in items where key(item) < key(best) {
        best = item
    }
    return best
}

assert(smallest(["pear", "fig", "banana"], by: { $0.count }) == "fig")
assert(smallest([3, -7, 5], by: { abs($0) }) == 3)
assert(smallest([String](), by: { $0.count }) == nil)

Two type parameters: T for the elements, which need nothing, and Key for the key’s type, which must be comparable. The standard library’s version is items.min(by:).

Q4: A generic pair

Write a generic structure Pair<T> holding first and second, with a method swapped() and a generic method map(_:) that applies a function to both values, possibly changing their type.

Show solution
struct Pair<T> {
    var first: T
    var second: T

    func swapped() -> Pair<T> {
        Pair(first: second, second: first)
    }

    func map<U>(_ transform: (T) -> U) -> Pair<U> {
        Pair<U>(first: transform(first), second: transform(second))
    }
}

let numbers = Pair(first: 1, second: 2)
assert(numbers.swapped().first == 2)
assert(numbers.map { "\($0)!" }.second == "2!")
assert(numbers.map { Double($0) / 2 }.first == 0.5)

map has its own type parameter U, separate from the structure’s T, because the result can hold a different type than the original.

Q5: Describable, retroactively

Declare a protocol Describable with a summary: String property, and make Int and String conform through extensions. Then write describeAll(_:), which takes an array of any Describable.

Show solution
protocol Describable {
    var summary: String { get }
}

extension Int: Describable {
    var summary: String { "the number \(self)" }
}

extension String: Describable {
    var summary: String { "the text \"\(self)\"" }
}

func describeAll(_ items: [any Describable]) -> String {
    items.map(\.summary).joined(separator: "; ")
}

assert(describeAll([3, "hi"]) == "the number 3; the text \"hi\"")
assert(describeAll([]) == "")

Int and String were written long before Describable, and you do not own their source, yet an extension can make them conform. \.summary is a key path, a short way to write { $0.summary }.

Q6 (optional): A generic tree

Write a generic tree indirect enum GTree<Element> with cases leaf and node (a label and an array of branches), a method map(_:) that transforms every label, and a property labels listing them in order.

Show solution
indirect enum GTree<Element> {
    case leaf(Element)
    case node(Element, [GTree<Element>])

    func map<U>(_ transform: (Element) -> U) -> GTree<U> {
        switch self {
        case .leaf(let label):
            .leaf(transform(label))
        case .node(let label, let branches):
            .node(transform(label), branches.map { $0.map(transform) })
        }
    }

    var labels: [Element] {
        switch self {
        case .leaf(let label): [label]
        case .node(let label, let branches): [label] + branches.flatMap(\.labels)
        }
    }
}

let tree = GTree.node(1, [.leaf(2), .node(3, [.leaf(4)])])
assert(tree.map { $0 * 10 }.labels == [10, 20, 30, 40])
assert(tree.map { String($0) }.labels.joined() == "1234")

One definition now covers trees of numbers, strings, or anything else, and map can turn one kind into another.

What’s next

Next lesson: iterators and lazy sequences, and sequences that never end.