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

Getting started

Run your first Swift program, evaluate expressions the way the computer does, and meet the two kinds of error you will see all course.

CS61A
Welcome · Composing Programs 1.1
Documentation
Swift documentation

CS61A opens with a claim: the most important idea in programming is abstraction, giving a name to something complicated so you can stop thinking about its details. This tutorial follows that course lecture by lecture, in Swift. Before abstraction, though, we need a program that runs.

Running Swift

Swift runs on macOS, Linux, and Windows. On a Mac, installing Xcode or the Command Line Tools gives you swift; on other systems, use the installer from swift.org/install. Check it worked:

swift --version

Save this line in a file called hello.swift:

print("Hello, world!")

Then run it:

swift hello.swift

That one line is a complete program. There is no main function to write and nothing to import: code at the top level of a file is where the program starts. Every lab in this tutorial works the same way. Put the code in a .swift file and run it with swift.

The REPL

For quick experiments, swift repl starts an interactive session, the equivalent of running python3 with no file. Type an expression, press Return, and Swift shows its value. Type :quit to leave. The REPL is great for checking one line; for anything longer, a file is easier to edit and rerun.

Expressions

A program is built from expressions, pieces of code that produce a value. The simplest expressions are values themselves:

print(2026)
print(3.14)
print("Swift")
print(true)

Operators combine values into bigger expressions. Arithmetic works as you expect, with one surprise: when both sides are whole numbers, / throws away the remainder, and % gives you the remainder.

print(7 + 2)    // 9
print(7 / 2)    // 3
print(7 % 2)    // 1
print(7.0 / 2)  // 3.5

What would Swift print?

print(17 / 5)
print(17 % 5)

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

Show answer and explanation

Answer3\n2

17 / 5 divides two integers, so the result is the integer 3; the remainder, 17 % 5, is 2. Each print writes its own line.

Precedence

As in mathematics, *, /, and % bind more tightly than + and -, and parentheses override both:

print(2 + 3 * 4)     // 14
print((2 + 3) * 4)   // 20

Integer division rounds toward zero, so the remainder takes the sign of the number being divided. This differs from Python, where -7 // 2 is -4:

print(-7 / 2, -7 % 2)   // -3 -1

What would Swift print?

print(10 / 4, 10 % 4, 10.0 / 4, -10 / 4)

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

Show answer and explanation

Answer2 2 2.5 -2

10 / 4 is 2 with remainder 2. With a Double on one side, the result is the exact 2.5. -10 / 4 rounds toward zero, giving -2 rather than -3.

Call expressions

A call expression applies a function to arguments. max and min come with Swift:

print(max(3, 9))           // 9
print(min(max(1, 5), 3))   // 3

CS61A’s rule for evaluating a call expression works for Swift too:

  1. Evaluate the function being called.
  2. Evaluate each argument, left to right.
  3. Apply the function to the argument values.

Arguments are evaluated before the call, so nested calls work from the inside out. In min(max(1, 5), 3), max(1, 5) becomes 5 first, and then min(5, 3) is 3.

What would Swift print?

print(max(2, min(8, 4), 3))

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

Show answer and explanation

Answer4

min(8, 4) is evaluated first and gives 4, so the call becomes max(2, 4, 3), which is 4. max accepts any number of arguments.

print can take several arguments too. It writes them separated by spaces:

print("Swift", 6, true)   // Swift 6 true

Types

Every value in Swift has a type. 2026 is an Int, 3.14 is a Double, "Swift" is a String, and true is a Bool. Swift checks types before your program runs, and it never converts between them silently.

What would Swift print?

let whole = 1
let fraction = 2.5
print(whole + fraction)

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

Show answer and explanation

AnswerError

whole is an Int and fraction is a Double, and Swift will not add them without being told how. The program does not compile. Writing Double(whole) + fraction makes the conversion explicit and prints 3.5.

A number written directly in the code is more flexible: in 1 + 2.5, Swift reads 1 as a Double because that is the only way the expression makes sense. The strictness applies to values that already have a type.

Strings can include values with interpolation: write \( and ) around any expression inside a string.

let language = "Swift"
let version = 6
print("\(language) \(version) was released with a new language mode.")

Comments

Anything after // on a line is a comment, ignored by Swift and written for people. /* and */ surround a comment that spans several lines:

// Seconds in a day.
let secondsPerDay = 24 * 60 * 60   /* 86,400 */
print(secondsPerDay)

Numbers have limits

An Int is a 64-bit integer. The largest one is Int.max, a little over nine quintillion. Python integers grow as large as needed; Swift integers do not. Going past the limit is not silently wrapped around. It stops the program, because a wrong answer is worse than no answer:

What would Swift print?

let biggest = Int.max
print(biggest + 1)

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

Show answer and explanation

AnswerError

Adding 1 to the largest Int overflows. Swift catches it (here even before running, because the values are known at compile time) instead of producing a meaningless negative number. When wrapping really is what you want, Swift has separate operators such as &+.

A Double can hold fractions and very large values, but only about 16 significant digits, in binary. Most decimal fractions cannot be stored exactly:

What would Swift print?

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)

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

Show answer and explanation

Answer0.30000000000000004 false

Neither 0.1 nor 0.2 is exactly representable in binary, and their rounded sum is not the double closest to 0.3. This is true in every language that uses standard floating-point numbers, Python included. Compare doubles with a tolerance, as Lesson 6 does, not with ==.

Two kinds of error

Swift reports mistakes at two different times.

  • A compile-time error stops the program before it starts. Type mismatches, misspelled names, and missing punctuation are all caught this way. Nothing runs, not even the lines before the mistake.
  • A runtime error happens while the program is running, when it tries something impossible. Swift stops the program immediately rather than continuing with a wrong value.
let scores = [90, 85, 77]
print(scores[3])   // there is no fourth score

The array has positions 0, 1, and 2, so asking for position 3 stops the program at run time. In “What would Swift print?” questions, the answer to both kinds of failure is Error.

Put the lines in order

Put these lines in order so the program prints 15.

  1. let b = a * 2
  2. print(c + 3)
  3. let a = 3
  4. let c = b + a * 2

Show the correct program
let a = 3
let b = a * 2
let c = b + a * 2
print(c + 3)

Lab 0: Getting started

Labs are where you write code. Create a file for each lab, write your answers, and run it with swift. Each solution ends with assert checks: lines that stop the program if a result is wrong, and do nothing if it is right. They play the role of CS61A’s doctests.

Each lab starts with a warm-up of “What would Swift print?” questions, then problems to write yourself. Problems marked optional are extra challenges.

Q0: What would Swift print?

What would Swift print?

print(3 + 4 * 2 - 1)

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

Show answer and explanation

Answer10

Multiplication first: 4 × 2 = 8, then 3 + 8 − 1 = 10.

What would Swift print?

print(17 % 5 + 17 / 5)

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

Show answer and explanation

Answer5

17 % 5 is 2 and 17 / 5 is 3, so the sum is 5.

What would Swift print?

let name = "Swift"
print("\(name) has \(name.count) letters")

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

Show answer and explanation

AnswerSwift has 5 letters

Interpolation evaluates each expression inside \( ), including name.count, and inserts the result into the string.

Q1: Your setup

Run swift --version and then swift hello.swift with the program above. If both work, you are ready for the rest of the course.

Q2: Seconds in a week

Write an expression for the number of seconds in a week, using only multiplication, and print it.

Show solution
let secondsPerWeek = 7 * 24 * 60 * 60
print(secondsPerWeek)
assert(secondsPerWeek == 604_800)

Underscores in a number literal are ignored by Swift; they only make large numbers easier to read.

Q3: Fix the program

This program is meant to print the average of three test scores, 84.0, but it does not compile. Find the problem and fix it without changing the scores.

let total = 90 + 85 + 77
let count = 3.0
print(total / count)
Show solution

total is an Int and count is a Double. Convert one of them:

let total = 90 + 85 + 77
let count = 3.0
let average = Double(total) / count
print(average)
assert(average == 84.0)

Making count an Int instead would compile too, but 252 / 3 would then use integer division. It happens to divide evenly here; with other scores it would silently drop the fraction.

Q4: Minutes and seconds

Given let total = 1000 seconds, print 16 minutes and 40 seconds, computing both numbers from total with / and %.

Show solution
let total = 1000
let minutes = total / 60
let seconds = total % 60
print("\(minutes) minutes and \(seconds) seconds")
assert(minutes == 16 && seconds == 40)

Integer division gives the whole minutes, and the remainder is what is left over. The same pair of operations converts any quantity into larger and smaller units.

Q5 (optional): The middle value

Given three numbers a, b, and c, write a single expression using only max and min that gives the one in the middle.

Show solution
func middle(_ a: Int, _ b: Int, _ c: Int) -> Int {
    max(min(a, b), min(max(a, b), c))
}

assert(middle(7, 2, 5) == 5)
assert(middle(1, 2, 3) == 2)
assert(middle(3, 3, 1) == 3)
assert(middle(9, 4, 4) == 4)

min(a, b) and max(a, b) sort the first two. If c is below the smaller one, the middle is min(a, b); otherwise it is c capped by the larger one. The solution wraps the expression in a function so it can be checked with several inputs. Functions are the next lesson.

What’s next

Next lesson: naming values with let and var, and defining your own functions.