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

Control

Booleans and short-circuiting, if and switch as statements and expressions, and repeating work with while and for-in loops.

CS61A
Control · Composing Programs 1.4–1.5

So far every program has run straight from top to bottom. Control lets a program choose what to do next and repeat work until it is done.

Boolean values

Comparisons produce a Bool, either true or false:

print(3 < 5)        // true
print(3 == 3.0)     // true
print("a" != "b")   // true

&& (and), || (or), and ! (not) combine them. Like Python’s and and or, && and || short-circuit: they stop as soon as the answer is known, and never evaluate the right side if they do not need it.

What would Swift print?

func loud() -> Bool {
    print("called")
    return true
}
print(false && loud())
print(true || loud())

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

Show answer and explanation

Answerfalse\ntrue

false && … is false no matter what comes after, so loud() is never called. The same goes for true || …. Nothing but the two results is printed.

Short-circuiting is useful for guarding a risky check: count > 0 && total / count > 10 never divides by zero.

Unlike Python, Swift has no “truthy” values. A condition must be a Bool: if 1 { … } is a compile-time error.

Conditional statements

An if statement runs a block only when its condition is true, with optional else if and else clauses. Braces are required, parentheses around the condition are not.

func describe(_ temperature: Int) -> String {
    if temperature < 0 {
        return "freezing"
    } else if temperature < 20 {
        return "cool"
    } else {
        return "warm"
    }
}
print(describe(-5), describe(12), describe(28))   // freezing cool warm

In Swift, if can also be an expression that produces a value, as long as every branch is a single expression of the same type:

let x = -4
let sign = if x < 0 { "negative" } else if x == 0 { "zero" } else { "positive" }
print(sign)   // negative

switch

switch compares one value against a list of patterns. Patterns can be single values, lists of values, or ranges:

let grade = 87
switch grade {
case 90...100:
    print("A")
case 80..<90:
    print("B")
default:
    print("C or below")
}

90...100 is a closed range that includes 100; 80..<90 stops before 90. There is no fall-through between cases, so no break is needed. Swift also insists that a switch is exhaustive: every possible value must match some case.

What would Swift print?

let n = 3
switch n {
case 1:
    print("one")
case 2:
    print("two")
}

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

Show answer and explanation

AnswerError

An Int could be any number, and nothing handles 3 or anything else. “switch must be exhaustive” is a compile-time error, so nothing runs. Adding a default: case fixes it.

Matching several values at once

A switch can match a tuple, testing several values together. _ matches anything. This makes the classic FizzBuzz a table of cases:

func fizzBuzz(_ n: Int) -> String {
    switch (n % 3, n % 5) {
    case (0, 0): "FizzBuzz"
    case (0, _): "Fizz"
    case (_, 0): "Buzz"
    default: String(n)
    }
}
print(fizzBuzz(9), fizzBuzz(10), fizzBuzz(15), fizzBuzz(7))   // Fizz Buzz FizzBuzz 7

Cases are tried from the top, so (0, 0) must come before the more general (0, _).

Early exits with guard

A guard statement checks a condition that must hold for the rest of the function, and its else block must leave (with return, for example):

func firstDivisor(_ n: Int) -> Int {
    guard n > 1 else {
        return n
    }
    var divisor = 2
    while n % divisor != 0 {
        divisor += 1
    }
    return divisor
}
print(firstDivisor(91), firstDivisor(13))   // 7 13

guard puts the special cases first and keeps the main work at the left margin, instead of nesting it inside an if.

Iteration

A while loop repeats its body as long as its condition is true. This is the CS61A example of computing Fibonacci numbers by walking forward:

func fib(_ n: Int) -> Int {
    var previous = 0
    var current = 1
    var k = 1
    while k < n {
        (previous, current) = (current, previous + current)
        k += 1
    }
    return n == 0 ? 0 : current
}
print(fib(10))   // 55

Assigning to a tuple updates both names at once, using the old values on the right. The ? : operator is a compact conditional expression: a ? b : c is b when a is true and c otherwise.

What would Swift print?

var i = 0
var total = 0
while i < 4 {
    i += 1
    total += i
}
print(i, total)

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

Show answer and explanation

Answer4 10

The loop runs with i becoming 1, 2, 3, and 4, adding each to total, so total is 10. When i is 4 the condition fails and the loop ends.

A for-in loop runs once for each element of a sequence, such as a range:

for k in 1...3 {
    print(k * k)
}
for k in stride(from: 10, to: 0, by: -3) {
    print(k, terminator: " ")   // 10 7 4 1
}
print()

terminator: replaces the newline that print normally adds. When you do not need the loop variable, write _: for _ in 1...3 { … }.

What would Swift print?

for k in 1..<4 {
    print(k, terminator: " ")
}
print()
for k in 1...4 where k % 2 == 0 {
    print(k)
}

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

Show answer and explanation

Answer1 2 3\n2\n4

1..<4 stops before 4, so the first loop prints 1 2 3 on one line. A where clause filters the second loop to even values of k.

Other loops

repeat-while checks its condition after the body, so the body always runs at least once:

var attempts = 0
repeat {
    attempts += 1
} while attempts < 0
print(attempts)   // 1, even though the condition was false from the start

Inside any loop, continue skips to the next pass and break leaves the loop. With nested loops, a label says which loop to leave:

search: for i in 1...3 {
    for j in 1...3 where i * j == 4 {
        print("found", i, j)   // found 2 2
        break search
    }
}

What would Swift print?

for i in 1...10 {
    if i % 2 == 0 {
        continue
    }
    if i > 7 {
        break
    }
    print(i, terminator: " ")
}
print()

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

Show answer and explanation

Answer1 3 5 7

Even numbers are skipped by continue. At i = 9, the odd number is greater than 7, so break ends the loop before printing it.

Put the lines in order

Put the lines in order so factorial(5) prints 120.

  1. var result = 1
  2. return result
  3. }
  4. print(factorial(5))
  5. }
  6. result *= k
  7. for k in 1...n {
  8. func factorial(_ n: Int) -> Int {

Show the correct program
func factorial(_ n: Int) -> Int {
    var result = 1
    for k in 1...n {
        result *= k
    }
    return result
}
print(factorial(5))

Lab 2: Control

Put your solutions in lab02.swift with the assert lines, and run it.

Q0: What would Swift print?

What would Swift print?

let x = 5
if x > 3 {
    print("big")
} else if x > 1 {
    print("medium")
}
print(x > 3 || x / 0 == 1)

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

Show answer and explanation

AnswerError

The if would print big, but the program never runs: x / 0 is a division by zero that Swift can see at compile time, since x is a constant. Short-circuiting happens at run time; the compiler still checks every expression.

What would Swift print?

var n = 3
while n > 0 {
    n -= 1
    if n == 1 {
        continue
    }
    print(n)
}

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

Show answer and explanation

Answer2\n0

n becomes 2 (printed), then 1 (skipped by continue), then 0 (printed). Then the condition fails.

What would Swift print?

let point = (0, 4)
switch point {
case (0, 0): print("origin")
case (_, 0): print("on the x-axis")
case (0, _): print("on the y-axis")
default: print("elsewhere")
}

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

Show answer and explanation

Answeron the y-axis

The first two patterns need a 0 in the second position. (0, _) matches any point whose first value is 0.

Q1: Falling factorial

fallingFactorial(n, k) multiplies the k consecutive numbers counting down from n: fallingFactorial(6, 3) is 6 × 5 × 4 = 120. When k is 0 the result is 1.

func fallingFactorial(_ n: Int, _ k: Int) -> Int {
    // your code here
}
Show solution
func fallingFactorial(_ n: Int, _ k: Int) -> Int {
    var total = 1
    var factor = n
    for _ in 0..<k {
        total *= factor
        factor -= 1
    }
    return total
}

assert(fallingFactorial(6, 3) == 120)
assert(fallingFactorial(4, 3) == 24)
assert(fallingFactorial(4, 1) == 4)
assert(fallingFactorial(4, 0) == 1)

0..<k runs the loop exactly k times, and zero times when k is 0, which leaves total at 1.

Q2: Sum of digits

Return the sum of the decimal digits of a non-negative integer. Use % 10 to get the last digit and / 10 to remove it.

func sumDigits(_ n: Int) -> Int {
    // your code here
}
Show solution
func sumDigits(_ n: Int) -> Int {
    var rest = n
    var total = 0
    while rest > 0 {
        total += rest % 10
        rest /= 10
    }
    return total
}

assert(sumDigits(10) == 1)
assert(sumDigits(4224) == 12)
assert(sumDigits(1234567890) == 45)
assert(sumDigits(0) == 0)

Q3: Double eights

Return true if a non-negative integer contains two 8s next to each other.

func doubleEights(_ n: Int) -> Bool {
    // your code here
}
Show solution
func doubleEights(_ n: Int) -> Bool {
    var rest = n
    var previous = -1
    while rest > 0 {
        let digit = rest % 10
        if digit == 8 && previous == 8 {
            return true
        }
        previous = digit
        rest /= 10
    }
    return false
}

assert(!doubleEights(8))
assert(doubleEights(88))
assert(doubleEights(2882))
assert(doubleEights(880088))
assert(!doubleEights(12345))
assert(!doubleEights(80808080))

return true inside the loop leaves the function immediately, as soon as the answer is known.

Q4: a plus the absolute value of b

In Swift, operators are functions too: + has type (Int, Int) -> Int. Fill in the blank so aPlusAbsB returns a + |b| without calling abs.

func aPlusAbsB(_ a: Int, _ b: Int) -> Int {
    let f: (Int, Int) -> Int = ______
    return f(a, b)
}
Show solution
func aPlusAbsB(_ a: Int, _ b: Int) -> Int {
    let f: (Int, Int) -> Int = b < 0 ? (-) : (+)
    return f(a, b)
}

assert(aPlusAbsB(2, 3) == 5)
assert(aPlusAbsB(2, -3) == 5)
assert(aPlusAbsB(-1, 4) == 3)
assert(aPlusAbsB(-1, -4) == 3)

When b is negative, subtracting it adds its absolute value. Wrapping an operator in parentheses, (-), refers to the operator’s function instead of using it. This is a preview of the next lesson, where functions are values.

Q5: Leap years

A year is a leap year if it is divisible by 4, except century years, which must be divisible by 400. Write isLeapYear(_:) as a single expression.

func isLeapYear(_ year: Int) -> Bool {
    // your code here
}
Show solution
func isLeapYear(_ year: Int) -> Bool {
    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}

assert(isLeapYear(2024))
assert(!isLeapYear(2026))
assert(!isLeapYear(1900))   // a century, not divisible by 400
assert(isLeapYear(2000))

The parentheses matter: && binds more tightly than ||, so without them the expression would mean something else.

Q6: FizzBuzz, joined

Using fizzBuzz from this lesson, write fizzBuzzLine(_:), which returns the results for 1 through n separated by spaces.

func fizzBuzzLine(_ n: Int) -> String {
    // your code here
}
Show solution
func fizzBuzz(_ n: Int) -> String {
    switch (n % 3, n % 5) {
    case (0, 0): "FizzBuzz"
    case (0, _): "Fizz"
    case (_, 0): "Buzz"
    default: String(n)
    }
}

func fizzBuzzLine(_ n: Int) -> String {
    var line = ""
    for k in 1...n {
        line += (k == 1 ? "" : " ") + fizzBuzz(k)
    }
    return line
}

assert(fizzBuzzLine(5) == "1 2 Fizz 4 Buzz")
assert(fizzBuzzLine(15).hasSuffix("13 14 FizzBuzz"))

Q7 (optional): Reverse the digits

Write reverseDigits(_:) for non-negative integers, using a loop and no strings: reverseDigits(1234) is 4321, and reverseDigits(1200) is 21.

Show solution
func reverseDigits(_ n: Int) -> Int {
    var rest = n
    var reversed = 0
    while rest > 0 {
        reversed = reversed * 10 + rest % 10
        rest /= 10
    }
    return reversed
}

assert(reverseDigits(1234) == 4321)
assert(reverseDigits(1200) == 21)
assert(reverseDigits(7) == 7)
assert(reverseDigits(0) == 0)

Each pass moves the last digit of rest onto the end of reversed. Multiplying by 10 makes room for it.

What’s next

Next lesson: functions that take functions as arguments and return them as results.