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
- Swift book
- A Swift Tour · The Basics
- 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)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)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:
- Evaluate the function being called.
- Evaluate each argument, left to right.
- 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))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)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)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)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.
let b = a * 2print(c + 3)let a = 3let 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)Show answer and explanation
Answer10
Multiplication first: 4 × 2 = 8, then 3 + 8 − 1 = 10.
What would Swift print?
print(17 % 5 + 17 / 5)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")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.