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

Names and functions

Bind names with let and var, define functions with argument labels, and see why a function that prints is different from one that returns.

CS61A
Functions · Composing Programs 1.2–1.3
Swift book
The Basics · Functions

Last lesson every value was written out in full. Programs get interesting when we can name things: a value we computed once, or a whole computation we want to repeat. Naming is the first means of abstraction.

Binding names

let binds a name to a value. After that, the name stands for the value:

let radius = 10.0
let pi = 3.14159
let area = pi * radius * radius
print(area)   // 314.159

A name bound with let is a constant: it cannot be rebound. When a value genuinely needs to change, use var for a variable:

var total = 0
total = total + 5
total += 5   // shorthand for total = total + 5
print(total) // 10

Prefer let. When a name cannot change, a reader never has to track what happened to it, and the compiler will tell you if you try.

What would Swift print?

let n = 5
n = 6
print(n)

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

Show answer and explanation

AnswerError

n was bound with let, so n = 6 is a compile-time error: “cannot assign to value: ‘n’ is a ‘let’ constant”. Nothing prints. Declaring it with var would print 6.

Types are inferred

let radius = 10.0 never says “this is a Double”; Swift infers it from the value. You can write the type yourself with an annotation, which is useful when the value alone would suggest a different type:

let count: Double = 3
print(count / 2)   // 1.5, because count is a Double

Defining functions

A function definition gives a name to a computation. It lists the parameters and their types, the type of the result after ->, and a body:

func square(_ x: Int) -> Int {
    return x * x
}

print(square(12))   // 144
print(square(square(3)))   // 81

When the body is a single expression, return can be left out: func square(_ x: Int) -> Int { x * x } means the same thing.

Calling a function follows the rule from last lesson: evaluate the arguments, then apply. Applying a user-defined function means binding its parameters to the argument values in a new, local frame, and evaluating the body there. The parameter x exists only while square runs.

What would Swift print?

func square(_ x: Int) -> Int { x * x }
let x = 3
print(square(x + 1), x)

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

Show answer and explanation

Answer16 3

The argument x + 1 is evaluated first, giving 4, and square binds its own parameter x to 4 in its own frame. The global x is untouched, so the second value printed is still 3.

Argument labels

Swift functions have argument labels, names written at the call site. By default the label is the parameter name:

func greet(person: String) -> String {
    "Hello, \(person)!"
}
print(greet(person: "Anna"))

You can give a separate label and parameter name, so the call reads like a sentence while the body uses a short name. An underscore means no label:

func divide(_ dividend: Int, by divisor: Int) -> Int {
    dividend / divisor
}
print(divide(17, by: 5))   // 3

Labels are part of the function’s name. Leaving one out is an error.

What would Swift print?

func increment(value: Int) -> Int { value + 1 }
print(increment(2))

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

Show answer and explanation

AnswerError

The label is value:, so the call must be increment(value: 2). Swift reports “missing argument label ‘value:’ in call”.

Default values

A parameter can have a default value, used when the caller leaves the argument out:

func greet(_ name: String, punctuation: String = "!") -> String {
    "Hello, \(name)\(punctuation)"
}
print(greet("Ada"))                     // Hello, Ada!
print(greet("Ada", punctuation: "?"))   // Hello, Ada?

Defaults keep common calls short without writing a second function. You have already used one: print’s terminator: defaults to a newline.

Any number of arguments

A variadic parameter, written with ... after its type, accepts zero or more arguments. Inside the function it is an array:

func average(_ numbers: Double...) -> Double {
    var total = 0.0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
print(average(1, 2, 3, 4))   // 2.5

max and print are variadic, which is how they take any number of arguments. Loops over arrays come properly in Lesson 3 and Lesson 9.

What would Swift print?

func label(_ text: String, times: Int = 2, separator: String = "-") -> String {
    var result = text
    for _ in 1..<times {
        result += separator + text
    }
    return result
}
print(label("ha"), label("ha", times: 3), label("ha", separator: " "))

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

Show answer and explanation

Answerha-ha ha-ha-ha ha ha

The first call uses both defaults. The second overrides times, and the third overrides only separator. Labeled arguments with defaults can be left out independently.

Returning several values

A function returns one value, but that value can be a tuple. Labels on the tuple’s elements let callers read them by name:

func divide(_ n: Int, by d: Int) -> (quotient: Int, remainder: Int) {
    (n / d, n % d)
}

let result = divide(17, by: 5)
print(result)             // (quotient: 3, remainder: 2)
print(result.remainder)   // 2

Naming

Swift’s API guidelines ask for names that read as English at the call site, where the function is used, not where it is defined. Names are lowerCamelCase. Labels do the grammatical work: divide(17, by: 5), greet("Ada", punctuation: "?"), celsius(fromFahrenheit: 212). A reader who has never seen the definition should be able to guess what the call does.

Pure functions and print

Some functions only compute a value: square, max, divide. Calling them twice with the same arguments gives the same result, and nothing else happens. CS61A calls these pure functions.

print is different. Its job is a side effect, writing to the screen, and the value it returns is empty. In Swift that empty value is written () and its type is called Void.

What would Swift print?

print(print("Hi"))

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

Show answer and explanation

AnswerHi\n()

The argument is evaluated first: the inner print("Hi") writes Hi and returns (). Then the outer print writes that value, (). This is the Swift version of a classic CS61A question, where Python prints None.

The difference matters when you build on a function. A function that returns its answer can be used inside a larger expression; one that only prints it cannot.

Put the lines in order

Put the lines in order. The function should return the quotient and remainder; the program should print (3, 2).

  1. let remainder = n - quotient * d
  2. let quotient = n / d
  3. }
  4. func divide(_ n: Int, by d: Int) -> (Int, Int) {
  5. return (quotient, remainder)
  6. print(divide(17, by: 5))

Show the correct program
func divide(_ n: Int, by d: Int) -> (Int, Int) {
    let quotient = n / d
    let remainder = n - quotient * d
    return (quotient, remainder)
}
print(divide(17, by: 5))

Lab 1: Functions

Write each function in a file lab01.swift, with the assert lines from the solution below it, and run swift lab01.swift. No output means every check passed.

Q0: What would Swift print?

What would Swift print?

func double(_ x: Int) -> Int { x * 2 }
func addOne(_ x: Int) -> Int { x + 1 }
print(double(addOne(3)), addOne(double(3)))

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

Show answer and explanation

Answer8 7

Arguments are evaluated first. addOne(3) is 4 and doubling gives 8; double(3) is 6 and adding one gives 7. Order of composition matters.

What would Swift print?

func show(_ x: Int) -> Int {
    print("show", x)
    return x
}
print(show(1) + show(2))

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

Show answer and explanation

Answershow 1\nshow 2\n3

Operands are evaluated left to right, and each call prints as it runs. Only after both have returned does the outer print write their sum.

What would Swift print?

func greet(_ name: String, punctuation: String = "!") -> String {
    "Hi, \(name)\(punctuation)"
}
print(greet("Grace", "?"))

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

Show answer and explanation

AnswerError

punctuation has a label, so the second argument must be written punctuation: "?". Without it, Swift reports an extra argument. A default value does not remove the label.

Q1: Fahrenheit to Celsius

Write celsius(fromFahrenheit:), which converts a Double temperature using C = (F − 32) × 5 / 9.

func celsius(fromFahrenheit f: Double) -> Double {
    // your code here
}
Show solution
func celsius(fromFahrenheit f: Double) -> Double {
    (f - 32) * 5 / 9
}

assert(celsius(fromFahrenheit: 212) == 100)
assert(celsius(fromFahrenheit: 32) == 0)
assert(celsius(fromFahrenheit: -40) == -40)

The label fromFahrenheit makes the call read as English, while the body uses the short parameter name f.

Q2: Two of three

Write twoOfThree(_:_:_:), which takes three positive integers and returns the sum of the squares of the two smallest. Use a single expression in the body. min and max may help.

func twoOfThree(_ i: Int, _ j: Int, _ k: Int) -> Int {
    // your code here
}
Show solution
func twoOfThree(_ i: Int, _ j: Int, _ k: Int) -> Int {
    i * i + j * j + k * k - max(i, j, k) * max(i, j, k)
}

assert(twoOfThree(1, 2, 3) == 5)
assert(twoOfThree(5, 3, 1) == 10)
assert(twoOfThree(10, 2, 8) == 68)
assert(twoOfThree(5, 5, 5) == 50)

Adding all three squares and subtracting the largest avoids working out which two are the smallest. Another single expression is min(i, j, k) * min(i, j, k) + ..., but finding the middle value is harder than removing the largest.

Q3: Print or return?

Here are two versions of the same function. Without running them, decide what each program prints. Then run them to check.

func shout(_ word: String) {
    print(word.uppercased())
}
func shouted(_ word: String) -> String {
    word.uppercased()
}

shout("hi")
print(shouted("hi") + "!")
Show solution

It prints HI and then HI!. shout writes the result itself and returns nothing, so it cannot be used inside +. shouted returns its result, so the caller can decide what to do with it: add an exclamation mark, compare it, or print it. Prefer the returning version unless printing is the function’s whole job.

Q4: Hours and minutes

Write hours(fromMinutes:), which returns a tuple labeled hours and minutes. hours(fromMinutes: 135) is 2 hours and 15 minutes.

func hours(fromMinutes total: Int) -> (hours: Int, minutes: Int) {
    // your code here
}
Show solution
func hours(fromMinutes total: Int) -> (hours: Int, minutes: Int) {
    (total / 60, total % 60)
}

let time = hours(fromMinutes: 135)
assert(time.hours == 2 && time.minutes == 15)
assert(hours(fromMinutes: 59) == (0, 59))

Tuples of comparable values can be compared with == directly.

Q5: Average of anything

Write a variadic mean(_:) that returns the average of any number of integers as a Double, and 0 when there are none.

func mean(_ values: Int...) -> Double {
    // your code here
}
Show solution
func mean(_ values: Int...) -> Double {
    if values.isEmpty {
        return 0
    }
    var total = 0
    for value in values {
        total += value
    }
    return Double(total) / Double(values.count)
}

assert(mean(1, 2, 3, 4) == 2.5)
assert(mean(7) == 7)
assert(mean() == 0)

Dividing by values.count when it is 0 would produce nan, “not a number”, so the empty case is handled first.

Q6 (optional): Round to the nearest multiple

Write roundToNearest(_:multiple:) for non-negative integers, rounding halves up: roundToNearest(17, multiple: 5) is 15, roundToNearest(18, multiple: 5) is 20. Use a single expression with integer arithmetic.

Show solution
func roundToNearest(_ x: Int, multiple m: Int) -> Int {
    (x + m / 2) / m * m
}

assert(roundToNearest(17, multiple: 5) == 15)
assert(roundToNearest(18, multiple: 5) == 20)
assert(roundToNearest(25, multiple: 10) == 30)
assert(roundToNearest(0, multiple: 7) == 0)

Adding half the multiple before dividing moves every number that is at least halfway to the next multiple past it; integer division then drops the rest, and multiplying rebuilds the multiple.

What’s next

Next lesson: choosing between options with if and switch, and repeating work with loops.