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

Mutation and value semantics

Changing data in place: why Swift arrays and structures are copied instead of shared, mutating methods, inout parameters, and how that differs from Python’s lists.

CS61A
Mutation · Composing Programs 2.4

CS61A’s Mutation lecture is full of surprises like this one, in Python:

>>> a = [1, 2]
>>> b = a
>>> b.append(3)
>>> a
[1, 2, 3]

a and b are two names for the same list, so changing it through one name changes what the other sees. This is called aliasing, and it causes a large share of bugs in Python programs.

Swift’s arrays, dictionaries, strings, and structures work differently.

Value semantics

What would Swift print?

var a = [1, 2]
var b = a
b.append(3)
print(a, b)

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

Show answer and explanation

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

In Swift, var b = a gives b its own copy of the array. Appending to b changes only b; a is still [1, 2]. This is the opposite of the Python example above.

A type has value semantics when assigning it, or passing it to a function, behaves like making a copy. Int, String, Array, Dictionary, Set, and every structure and enumeration you define have value semantics. Two variables never secretly share one of these.

Copying a large array sounds slow, and Swift avoids actually copying until it must. The two arrays share storage until one of them is changed, and only then is the copy made. This is called copy-on-write; it keeps the simple rule without the cost.

Nested values are copies too:

What would Swift print?

var grid = [[0, 0], [0, 0]]
var row = grid[0]
row[0] = 7
grid[1][1] = 5
print(grid, row)

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

Show answer and explanation

Answer[[0, 0], [0, 5]] [7, 0]

row is a copy of the first row, so changing it leaves grid alone. Changing grid[1][1] directly does change grid. In Python, row would have been an alias for the inner list, and grid would show the 7.

Where mutation is allowed

Because values are copied, Swift can check at compile time which code is allowed to change which values.

  • A name bound with let can never be changed, including its properties and elements.
  • A function’s parameters are constants. Changing an array argument inside a function is a compile-time error.

What would Swift print?

func addZero(_ values: [Int]) {
    values.append(0)
}
var numbers = [1]
addZero(numbers)
print(numbers)

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

Show answer and explanation

AnswerError

values is a parameter, and parameters are constants: “cannot use mutating member on immutable value”. The function receives a copy it cannot change. To return a changed array, copy it into a var, change that, and return it.

mutating methods

A method that changes a structure’s properties must be marked mutating, and it can only be called on a var:

struct Counter {
    private(set) var count = 0

    mutating func increment() {
        count += 1
    }
}

var clicks = Counter()
clicks.increment()
clicks.increment()
print(clicks.count)   // 2

private(set) lets other code read count but not assign it, so the only way to change it is through increment(). Calling increment() on a let counter is a compile-time error: the mutating keyword is how the compiler knows the call would change it.

inout parameters

Sometimes a function’s job really is to change its caller’s variable. An inout parameter allows it, and the caller writes & to show the variable may be changed:

func double(_ values: inout [Int]) {
    for i in values.indices {
        values[i] *= 2
    }
}

var numbers = [1, 2, 3]
double(&numbers)
print(numbers)   // [2, 4, 6]

The & at the call site is the point: you can see, reading the call, that numbers is about to change. Mutation in Swift is always visible where it happens.

What would Swift print?

func swapTwo(_ x: inout Int, _ y: inout Int) {
    (x, y) = (y, x)
}
var a = 1
var b = 2
swapTwo(&a, &b)
print(a, b)

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

Show answer and explanation

Answer2 1

Both parameters are inout, so the function swaps the caller’s variables themselves. Without inout, it would swap its own copies and nothing would change.

In-place algorithms

Many array operations come in two forms: one that returns a new array and one that changes the array in place. sorted() and sort(), reversed() and reverse(). swapAt(_:_:) exchanges two elements, which is the building block of most in-place algorithms:

var numbers = [3, 1, 2]
numbers.sort()
print(numbers)          // [1, 2, 3]
numbers.swapAt(0, 2)
print(numbers)          // [3, 2, 1]

In-place versions save memory by not building a second array. With value semantics, they are still safe: only the variable you call them on changes.

A shared object inside a value

A structure that stores a class instance copies the reference, not the object. Two copies of the structure then share one object:

What would Swift print?

final class Box {
    var value = 0
}
struct Holder {
    var box = Box()
}
var first = Holder()
let second = first
first.box.value = 5
print(second.box.value)

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

Show answer and explanation

Answer5

Copying first copied its box property, which is a reference. Both holders point to the same Box, so the change made through first is visible through second. Value semantics goes only as deep as the values.

This is the one place where Python’s aliasing surprise can reappear in Swift. The standard library’s arrays and dictionaries avoid it with copy-on-write; your own types should too, or should use only value types inside.

Put the lines in order

Put the lines in order. The method must be mutating; the program prints 3.

  1. }
  2. count += 1
  3. mutating func increment() {
  4. counter.increment()
  5. print(counter.count)
  6. var counter = Counter()
  7. }
  8. for _ in 1...3 {
  9. var count = 0
  10. struct Counter {
  11. }

Show the correct program
struct Counter {
    var count = 0
    mutating func increment() {
        count += 1
    }
}
var counter = Counter()
for _ in 1...3 {
    counter.increment()
}
print(counter.count)

Mutation is still useful

None of this means mutation is bad. Building up a result in a var inside a function, as in every lab so far, is mutation, and it is perfectly safe: nothing outside the function can see the changes until the value is returned. What value semantics removes is surprising mutation, a change made in one place showing up in another.

Some things really should be shared: a bank account, a network connection, a game’s single world. For those, Swift has classes, the topic of the next lesson.

Lab 13: Mutation

Q0: What would Swift print?

What would Swift print?

var original = ["a": [1, 2]]
var copy = original
copy["a"]!.append(3)
print(original["a"]!, copy["a"]!)

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

Show answer and explanation

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

The dictionary and the arrays inside it are all values. Changing the array in copy leaves original untouched.

What would Swift print?

func appendZero(_ values: inout [Int]) {
    values.append(0)
}
var numbers = [1]
appendZero(&numbers)
appendZero(&numbers)
print(numbers)

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

Show answer and explanation

Answer[1, 0, 0]

Each call changes the caller’s array, because the parameter is inout and the call passes &numbers.

What would Swift print?

struct Counter {
    var count = 0
    mutating func increment() { count += 1 }
}
let counter = Counter()
counter.increment()
print(counter.count)

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

Show answer and explanation

AnswerError

counter is a let, and increment is mutating, so the call is a compile-time error.

Q1: Remove the odd numbers

Write removeOdd(_:), which removes every odd number from an array in place.

func removeOdd(_ values: inout [Int]) {
    // your code here
}
Show solution
func removeOdd(_ values: inout [Int]) {
    values.removeAll { $0 % 2 != 0 }
}

var numbers = [1, 2, 3, 4, 5, -3]
removeOdd(&numbers)
assert(numbers == [2, 4])

var empty: [Int] = []
removeOdd(&empty)
assert(empty == [])

removeAll(where:) removes every element for which the closure returns true. Testing != 0 rather than == 1 handles negative odd numbers, whose remainder is −1.

Q2: A bounded counter

Write a structure BoundedCounter with a limit set when it is created, a read-only count starting at 0, a mutating increment() that stops at the limit, and a mutating reset().

Show solution
struct BoundedCounter {
    let limit: Int
    private(set) var count = 0

    init(limit: Int) {
        self.limit = limit
    }

    mutating func increment() {
        count = min(count + 1, limit)
    }

    mutating func reset() {
        count = 0
    }
}

var counter = BoundedCounter(limit: 2)
counter.increment()
counter.increment()
counter.increment()
assert(counter.count == 2)

var copy = counter
copy.reset()
assert(copy.count == 0)
assert(counter.count == 2)   // the original is unaffected

The last two assertions show value semantics: resetting copy does not touch counter.

Q3: Rotate in place

Write rotateLeft(_:), which moves the first element of an array to the end, in place. An empty array is left unchanged.

func rotateLeft(_ values: inout [Int]) {
    // your code here
}
Show solution
func rotateLeft(_ values: inout [Int]) {
    guard !values.isEmpty else {
        return
    }
    let first = values.removeFirst()
    values.append(first)
}

var numbers = [1, 2, 3, 4]
rotateLeft(&numbers)
assert(numbers == [2, 3, 4, 1])
rotateLeft(&numbers)
assert(numbers == [3, 4, 1, 2])

var none: [Int] = []
rotateLeft(&none)
assert(none == [])

removeFirst() removes and returns the first element, and would stop the program on an empty array, which is why the guard comes first.

Q4: Bubble sort

Write bubbleSort(_:), which sorts an array in place by repeatedly swapping adjacent elements that are out of order. After each pass, the largest remaining element has “bubbled” to the end.

func bubbleSort(_ values: inout [Int]) {
    // your code here
}
Show solution
func bubbleSort(_ values: inout [Int]) {
    guard values.count > 1 else {
        return
    }
    for end in stride(from: values.count - 1, to: 0, by: -1) {
        for i in 0..<end where values[i] > values[i + 1] {
            values.swapAt(i, i + 1)
        }
    }
}

var numbers = [5, 1, 4, 2, 8]
bubbleSort(&numbers)
assert(numbers == [1, 2, 4, 5, 8])
var single = [1]
bubbleSort(&single)
assert(single == [1])

Each pass can stop one position earlier than the last, because the end of the array is already sorted. Bubble sort compares every pair in the worst case, which Lesson 18 will call quadratic; sort() is much faster.

Q5: Reverse in place

Write reverseInPlace(_:), which reverses an array by swapping elements from the two ends toward the middle. Do not use reverse() or reversed().

func reverseInPlace(_ values: inout [Int]) {
    // your code here
}
Show solution
func reverseInPlace(_ values: inout [Int]) {
    var left = 0
    var right = values.count - 1
    while left < right {
        values.swapAt(left, right)
        left += 1
        right -= 1
    }
}

var numbers = [1, 2, 3, 4, 5]
reverseInPlace(&numbers)
assert(numbers == [5, 4, 3, 2, 1])
var empty: [Int] = []
reverseInPlace(&empty)
assert(empty == [])

With an odd number of elements, the middle one stays where it is; with an empty array, right starts at −1 and the loop never runs.

Q6 (optional): A matrix with a mutating transpose

Write a structure Matrix storing rows: [[Int]], with a mutating func transpose() that swaps rows and columns in place.

Show solution
struct Matrix {
    var rows: [[Int]]

    mutating func transpose() {
        guard let first = rows.first else {
            return
        }
        rows = (0..<first.count).map { column in rows.map { $0[column] } }
    }
}

var m = Matrix(rows: [[1, 2], [3, 4], [5, 6]])
let before = m
m.transpose()
assert(m.rows == [[1, 3, 5], [2, 4, 6]])
assert(before.rows == [[1, 2], [3, 4], [5, 6]])   // the copy is unaffected

“In place” here means the method changes m rather than returning a new matrix. It builds the new rows first and then replaces the property; changing the rows while reading them would mix old and new values.

What’s next

Next lesson: classes, the reference types used when something should be shared.