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

Optionals

Represent a value that might be missing with an optional, and unwrap it safely with if let, guard let, ??, and optional chaining.

CS61A
Containers (Swift-specific)
Documentation
Optional

Some questions have no answer. The first element of an empty array. The number written in the string "four". The value for a key that is not in a dictionary. Python answers these with None, and a program that forgets to check crashes much later with a confusing error.

Swift makes “might be missing” part of the type. That is what the ? and ! in the last two lessons were about.

Optional types

Int? is an optional Int: either an Int, or nil, meaning no value. Int("42") returns an Int? because the conversion can fail:

let parsed = Int("42")    // Int?, holding 42
let failed = Int("four")  // Int?, holding nil
print(parsed as Any, failed as Any)   // Optional(42) nil

An Int? is not an Int, and Swift will not let you use it as one:

What would Swift print?

let n: Int? = 5
print(n + 1)

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

Show answer and explanation

AnswerError

n might be nil, and nil + 1 has no meaning, so Swift refuses to compile it: “value of optional type ‘Int?’ must be unwrapped”. Before using the number, the program has to say what happens when there isn’t one.

That compile-time error is the whole point. Every place a value might be missing is visible in the code, and the compiler makes you handle it.

Unwrapping

if let

if let runs a block only when the optional holds a value, binding that value to a name of the non-optional type:

let input = "42"
if let number = Int(input) {
    print(number + 1)          // number is an Int here
} else {
    print("not a number")
}

When the new name is the same as the optional’s, if let number is enough. Several optionals can be unwrapped at once, with extra conditions:

let first = Int("3"), second = Int("x")
if let first, let second {
    print(first + second)
} else {
    print("missing")           // second is nil
}

guard let

guard let unwraps for the rest of the function, and requires the else branch to leave. It keeps the normal path unindented:

func greet(_ name: String?) -> String {
    guard let name else {
        return "Hello, stranger"
    }
    return "Hello, \(name)"
}
print(greet("Ada"), "/", greet(nil))

?? and !

?? supplies a default when the optional is nil:

What would Swift print?

let a = Int("3")
let b = Int("x")
print(b ?? a ?? 0, (b ?? 1) + 1)

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

Show answer and explanation

Answer3 2

b is nil, so b ?? a ?? 0 falls through to a, which is 3. In the second expression, b ?? 1 is 1, and adding 1 gives 2.

! force-unwraps: it takes the value out, and stops the program if there isn’t one. It is a promise to the compiler that you know better.

What would Swift print?

let empty: [Int] = []
print(empty.first!)

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

Show answer and explanation

AnswerError

empty.first is nil, and force-unwrapping nil is a runtime error: “Unexpectedly found nil while unwrapping an Optional value”. Use ! only when nil is truly impossible, and prefer if let or ?? otherwise.

Optional chaining

?. calls a method or reads a property only if the value is there. If anything along the chain is nil, the whole chain is nil:

let words = ["swift", "optional"]
print(words.first?.uppercased() ?? "none")   // SWIFT

let nothing: [String] = []
print(nothing.first?.uppercased() ?? "none") // none

map does the same for a single transformation, and compactMap applies a function that returns optionals to a whole sequence, keeping only the values:

print(Int("7").map { $0 * 2 } ?? 0)              // 14
print(["1", "two", "3"].compactMap { Int($0) })   // [1, 3]

What would Swift print?

let scores = ["Ada": [90, 85]]
print(scores["Ada"]?.first ?? 0, scores["Alan"]?.first ?? 0)

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

Show answer and explanation

Answer90 0

scores["Ada"] is an optional array; ?.first reads its first element, 90. scores["Alan"] is nil, so the whole chain is nil and ?? gives 0.

Switching on an optional

An optional is an enumeration with two cases, so switch can take it apart. case let n? matches a value and binds it; case nil matches the absence. A where clause adds a condition:

func describe(_ input: String) -> String {
    switch Int(input) {
    case let n? where n > 10:
        "big number \(n)"
    case let n?:
        "small number \(n)"
    case nil:
        "not a number"
    }
}
print(describe("12"), "/", describe("3"), "/", describe("x"))

Going several levels deep

Chains can go through several optional steps, such as a dictionary whose values are dictionaries. The whole chain stops at the first nil:

let people: [String: [String: Int]] = ["ada": ["age": 36]]
print(people["ada"]?["age"] ?? -1)   // 36
print(people["bob"]?["age"] ?? -1)   // -1, stopped at "bob"

compactMap is the tool for “apply a function that might fail, and keep the successes”. It differs from flatMap, which joins arrays of arrays:

print(["1", "x", "3"].compactMap { Int($0) })   // [1, 3]
print([[1, 2], [3]].flatMap { $0 })             // [1, 2, 3]

Put the lines in order

Put the lines in order. The function returns nil when dividing by zero; the program prints 3 and then -1.

  1. }
  2. func safeDivide(_ a: Int, _ b: Int) -> Int? {
  3. print(safeDivide(1, 0) ?? -1)
  4. print(safeDivide(7, 2) ?? -1)
  5. return a / b
  6. guard b != 0 else {
  7. }
  8. return nil

Show the correct program
func safeDivide(_ a: Int, _ b: Int) -> Int? {
    guard b != 0 else {
        return nil
    }
    return a / b
}
print(safeDivide(7, 2) ?? -1)
print(safeDivide(1, 0) ?? -1)

Lab 10: Optionals

Q0: What would Swift print?

What would Swift print?

let scores = ["ada": 90]
if let score = scores["ada"], score > 80 {
    print("pass", score)
}
print(scores["grace"] ?? 0)

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

Show answer and explanation

Answerpass 90\n0

The if let unwraps 90, and the extra condition holds. The missing key gives nil, replaced by 0.

What would Swift print?

let words = ["swift", "is", "fun"]
print(words.first(where: { $0.count > 5 }) ?? "none", words.last?.count ?? 0)

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

Show answer and explanation

Answernone 3

No word is longer than five characters, so first(where:) is nil and the default is used. The last word, "fun", has three characters.

What would Swift print?

var name: String? = "Ada"
name = nil
print(name!.count)

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

Show answer and explanation

AnswerError

name is nil by the time it is force-unwrapped, which stops the program.

Q1: Safe division

Write safeDivide(_:_:), returning nil when the divisor is zero and the integer quotient otherwise.

func safeDivide(_ a: Int, _ b: Int) -> Int? {
    // your code here
}
Show solution
func safeDivide(_ a: Int, _ b: Int) -> Int? {
    b == 0 ? nil : a / b
}

assert(safeDivide(7, 2) == 3)
assert(safeDivide(1, 0) == nil)
assert(safeDivide(0, 5) == 0)

An Int? can be compared with == against a number or nil directly.

Q2: The first repeat

Write firstRepeated(_:), which returns the first value that appears for a second time in the array, or nil if every value is different.

func firstRepeated(_ values: [Int]) -> Int? {
    // your code here
}
Show solution
func firstRepeated(_ values: [Int]) -> Int? {
    var seen: Set<Int> = []
    for value in values {
        if seen.contains(value) {
            return value
        }
        seen.insert(value)
    }
    return nil
}

assert(firstRepeated([3, 1, 4, 1, 5, 3]) == 1)   // 1 repeats before 3 does
assert(firstRepeated([1, 2, 3]) == nil)
assert(firstRepeated([]) == nil)

Q3: Sum of the numbers

Write sumOfNumbers(_:), which adds up the strings in an array that are valid integers and ignores the rest. Use no loops.

func sumOfNumbers(_ strings: [String]) -> Int {
    // your code here
}
Show solution
func sumOfNumbers(_ strings: [String]) -> Int {
    strings.compactMap { Int($0) }.reduce(0, +)
}

assert(sumOfNumbers(["1", "two", "3"]) == 4)
assert(sumOfNumbers(["-5", "5", "five"]) == 0)
assert(sumOfNumbers([]) == 0)

compactMap does the unwrapping: failed conversions are nil and are dropped, and only the numbers reach reduce.

Q4: Your own firstIndex

Write firstIndex(of:in:), which returns the position of the first element equal to value, or nil. Do not use the built-in firstIndex.

func firstIndex(of value: Int, in values: [Int]) -> Int? {
    // your code here
}
Show solution
func firstIndex(of value: Int, in values: [Int]) -> Int? {
    for (index, element) in values.enumerated() where element == value {
        return index
    }
    return nil
}

assert(firstIndex(of: 7, in: [4, 7, 9, 7]) == 1)
assert(firstIndex(of: 5, in: [4, 7, 9]) == nil)
assert(firstIndex(of: 1, in: []) == nil)

Q5: Parsing a date

Write parseDate(_:), which turns a string like "2026-09-27" into a tuple of year, month, and day, or nil if it is not three numbers separated by - with a month from 1 to 12 and a day from 1 to 31.

func parseDate(_ text: String) -> (year: Int, month: Int, day: Int)? {
    // your code here
}
Show solution
func parseDate(_ text: String) -> (year: Int, month: Int, day: Int)? {
    let parts = text.split(separator: "-").compactMap { Int($0) }
    guard parts.count == 3, (1...12).contains(parts[1]), (1...31).contains(parts[2]) else {
        return nil
    }
    return (parts[0], parts[1], parts[2])
}

assert(parseDate("2026-09-27")! == (2026, 9, 27))
assert(parseDate("2026-13-01") == nil)
assert(parseDate("hello") == nil)
assert(parseDate("2026-9") == nil)

compactMap drops any part that is not a number, so the single count == 3 check catches both missing parts and non-numeric ones. A full date checker would also know that April has 30 days.

Q6 (optional): The largest of the known values

Write maxKnown(_:), which returns the largest non-nil value in an array of optionals, or nil if there is none. One line is enough.

Show solution
func maxKnown(_ values: [Int?]) -> Int? {
    values.compactMap { $0 }.max()
}

assert(maxKnown([3, nil, 8, nil]) == 8)
assert(maxKnown([nil, nil]) == nil)
assert(maxKnown([]) == nil)

compactMap { $0 } unwraps every value and drops the nils; max() of an empty array is itself nil, so both kinds of “nothing” come out the same.

What’s next

Next lesson: defining your own types with structures and enumerations.