Part 1 of 4 of the series "Native iOS Engineering".
You open a to-do app, type "buy milk" and save it. You switch to another app for an hour and, when
you come back, the task is still there, even if the system closed the app in the meantime. Two
things make that work, and this part teaches both: a language that won't let you read a value that
doesn't exist, and a system that tells your app before moving it to the background (off screen,
not in use).
Swift turns many runtime surprises (while the program runs) into decisions you make when you
compile (when the compiler translates your code into a program). This part takes you from your
first constant to memory management, and ends in the simulator, with
the life of an iOS app. The rest of the series builds Native Task
Manager, a to-do app, so the examples use tasks wherever they can.
Wondering whether iOS is for you, or what you'll be able to do by the end? The two boxes below
answer that: open them with a click.
Going deeper
is iOS for you? A native app is written with the platform's own language and
frameworks (libraries that bring their own way of organizing the program; on iOS, Swift and
SwiftUI) and reaches everything the phone offers directly. A web app runs inside the browser. A
cross-platform app (React Native, Flutter) is written once for iOS and Android with its own
framework; part
3
compares React Native with Swift.
An iOS developer spends the day building screens, wiring them to data and the network, asking
for permissions, writing tests and fixing what people report. To start you need a Mac and Xcode,
Apple's development environment, which is free; you can follow the language half of this guide
on Linux too. Publishing on the App Store requires the Apple Developer Program, which costs 99
US dollars a year. If you like a compiler that warns you before something breaks, caring about
how a screen looks and feels, or building something people carry in their pocket, this is for
you.
Going deeper
what you'll be able to do by the end of this part.
declare constants and variables with the right type, and explain why Swift rejects an implicit
conversion or an overflow;
choose between arrays, dictionaries and sets, and predict what happens when you copy them;
unwrap an optional without forcing it, and say when forcing it is acceptable;
choose between a struct, a class and an enumeration for a model;
find and break a retain cycle, and check that the object was freed;
write a function that throws errors, let an error travel on to the caller, and handle it in
three ways;
create a SwiftUI app in Xcode, follow its life cycle, and declare its resources and permissions;
answer the most common interview questions about all of the above.
I ran all of the code, and what you see under each example is what it printed; the error messages
are the compiler's, copied from its output. Getting those messages wrong is part of the path: each
section shows you the typical mistake before you make it.
Going deeper
how I verified it. The language examples ran with Swift 6.4.2 on Linux, in the
official Swift image for Docker and with no network, compiled in Swift 6 mode; each program ran
three times and all three gave the same output. The iOS examples ran with Xcode 27.2 (27B52), the
iOS 27.2 SDK (the libraries and tools for building for that version) and an iPhone 17 simulator with iOS 27.2, with tests that pass. Where I give no
performance numbers, it's because I didn't measure them.
Before You Start
This is what you'll build in part 4: the finished Native Task Manager, with its task list, filter
and form.
Native Task Manager at the end of part 4.
For the language, from "Constants, Variables, and Initialization" to «Errors», the
terminal on macOS or Linux is enough; from «Anatomy of an iOS App» on, you
need Xcode. To run an example:
swiftc is the compiler; -swift-version 6 picks the Swift 6 language mode, the one the whole
series uses. Every program in this part can be downloaded with its expected output:
fundamentals and
interview exercises. The title of each code block is the file that ran.
Going deeper
the series, what it leaves out, and how to run Swift.
Part
Level
What you learn
1
From scratch
Swift (values, collections, optionals, types, memory, and errors) and the life of an iOS app
2
Intermediate
SwiftUI, networking with URLSession, Swift 6 concurrency, and MVVM architecture
3
Advanced
Local data and the Keychain, caching, testing, debugging, performance, and fifteen real problems
4
Practice
Native Task Manager from an empty folder to a tested app, in twelve steps
URLSession is Apple's networking tool; MVVM, a way to organize screens by separating the view
from its logic; the Keychain, the system's encrypted store for passwords; a cache, a nearby copy of
data so you don't fetch it again. Left out on purpose: UIKit in depth, Combine, App Store
publishing, widgets, CloudKit, building your own packages, and watchOS and visionOS.
Swift runs three ways: in the terminal (Xcode 27.2 ships Swift 6.4; on Linux, swift.org publishes
the same compiler and an image for Docker, a program that runs software in an isolated
container), in an Xcode playground (a file that runs the code as you write it), or
in an app project. swift --version tells you yours:
$ swift --versionswift-driver version: 1.168.6 Apple Swift version 6.4.2 (swiftlang-6.4.2.1.9 clang-2100.4.1.1)Target: arm64-apple-macosx27.2.0
The language mode isn't the compiler version: the compiler is the program (6.4.2) and the mode is
the set of rules it compiles your code with (6, 5, 4.2, or 4). In Swift 6 mode the compiler also
checks that two parts of the program running at the same time don't touch the same data without
coordinating; that's part 2.
Constants, Variables, and Initialization
What happens if you read a variable nobody assigned? In many languages, you get whatever is in that
memory. In Swift, the program doesn't compile. It all starts with how you declare a named value, and
Swift has two words for that. let declares a
constant: a name whose value is assigned once and can't be reassigned. var declares a
variable, which can.
LetVar.swift
let apples = 1 // a constant: it can't be reassignedvar basket = 0 // a variable: it canbasket += appleslet total: Int // declared without a value...let hasBonus = basket > 0if hasBonus { total = basket + 2 // ...and assigned on every path before it's read} else { total = basket}print("total:", total)let price = 4.5let name = "Ana"print(type(of: total), type(of: price), type(of: name))
total: 3Int Double String
Walk through it line by line:
apples is a constant: it's 1 forever. basket is a variable: it starts at 0 and the line
basket += apples adds 1 to it.
let total: Int declares a constant with no value yet. : Int is a type annotation: you
tell the compiler that total holds an integer.
The if assigns total in both branches. That's why the print can read it: whatever happens,
by the time the program gets there, total already has a value.
price and name have no annotation. The compiler looks at the initial value (4.5, "Ana")
and works out the type. type(of:) confirms it: Int, Double, and String.
That last point is type inference: the compiler works out a value's type at compile time, from
how you initialize it. It doesn't make Swift a dynamic language: price is a Double from the
moment it's compiled and can't start holding text. You type less, but every name still has a fixed
type.
Why It Matters: A Value Is Never Read Uninitialized
Step 3 looks like a detail, and it's one of the language's core guarantees.
Definite initialization is the rule by which the compiler checks that every value has been assigned before
it's first read, on every possible path through the program. It's part of Swift's memory safety,
the guarantee that your program doesn't read or write memory that isn't its own: in a language
without that rule, reading an uninitialized variable can return whatever happened to be left in that
spot in memory.
The usual mistake: declaring without a value and assigning in only one branch. The compiler
won't let it through:
ReadBeforeAssign.swift
let hasBonus = Bool.random()let total: Intif hasBonus { total = 3}print(total)
errores/ReadBeforeAssign.swift:6:7: error: constant 'total' used before being initialized1 | let hasBonus = Bool.random()2 | let total: Int | `- note: constant defined here3 | if hasBonus {4 | total = 35 | }6 | print(total) | `- error: constant 'total' used before being initialized7 |
If hasBonus is false, total would reach the print without a value. The fix is to assign it
on every path, as in LetVar.swift, or give it an initial value.
And a constant can't be reassigned or modified. With an array (a list of values, which I explain in
"Collections") you notice right away:
LetImmutable.swift
let scores = [1]scores.append(2)
errores/LetImmutable.swift:2:8: error: cannot use mutating member on immutable value: 'scores' is a 'let' constant1 | let scores = [1] | `- note: change 'let' to 'var' to make it mutable2 | scores.append(2) | `- error: cannot use mutating member on immutable value: 'scores' is a 'let' constant3 |
The message says exactly what's wrong, and the note offers the way out: change let to var.
let or var?
Always start with let and switch to var only when the value has to change. The opposite, var
"just in case", forces whoever reads your code to hunt for whether the value changes somewhere. The
compiler helps you: if you declare a var you never modify, it warns you and suggests let.
If you come from JavaScript or TypeScript. Swift's let and JavaScript's const look alike,
but they aren't the same. In JavaScript, const fixes the binding, the link between the name
and what it names: the name can't point to another array, but you can still add elements to the
array with push.
In Swift, an array is a value type, one that's copied when assigned (I explain it in
"Collections"), and let fixes the entire value: that's why append fails in the example
above. The comparison becomes exact with Swift's classes, which are reference types (shared
instead of copied): there, let fixes only the reference and the object (the value created from a class) can
still be modified,
just like const in JavaScript. You'll see it in "Structs and Classes".
What to take away: start with let; the compiler never lets you read something with no value.
Check what you learned. Does this code compile: let x: Int, then if c { x = 1 }, and then
print(x)?
Solution
No. If c is false, x reaches the print without a value, and definite
initialization requires it to have one on every path. It's the same error as
ReadBeforeAssign.swift: "constant 'x' used before being initialized".
Types and Operators
What's 7 divided by 2? In Swift it depends on the types of the 7 and the 2, and the language won't
choose for you. The everyday types are Int (integer), Double (a number with decimals), Bool (true or false), String (text), and Character (a single character).
Types.swift
let sum = 7let count = 2let average = Double(sum) / Double(count) // convert on purpose, never implicitlyprint("average:", average)let pi = 3 + 0.14 // the literal 3 has no type of its own: here it becomes a Doubleprint("pi:", pi)let top = Int8.max // the largest Int8: 127print("top:", top, "wrapped:", top &+ 1) // &+ wraps around on purposeprint("closed:", (1...3).count, "half-open:", (1..<3).count)let accented = "e\u{301}" // "e" followed by a combining acute accentprint(accented, "count:", accented.count, "scalars:", accented.unicodeScalars.count)
Three ideas in that program are enough to start; the other two are in the boxes.
No implicit conversions. In Swift a value never changes type on its own, not even between
numbers. To divide two integers and get a decimal, you convert each one with Double(_:). That
wipes out the rounding nobody asked for.
A literal has no type of its own.3 + 0.14 compiles: the 3 written in the code is a
literal, and the compiler gives it the type the context asks for, here Double. What doesn't
compile is mixing two values that already have a type:
The usual mistake: computing an average with an integer total and a decimal count.
ImplicitConversion.swift
let sum = 7let count = 2.0let average = sum / count
errores/ImplicitConversion.swift:3:19: error: binary operator '/' cannot be applied to operands of type 'Int' and 'Double'1 | let sum = 72 | let count = 2.03 | let average = sum / count | |- error: binary operator '/' cannot be applied to operands of type 'Int' and 'Double' | `- note: overloads for '/' exist with these partially matching parameter lists: (Double, Double), (Duration, Double), (Int, Int)4 |
sum is already an Int and count is already a Double: there's no division between the two.
The note lists the ones that do exist. The fix is to convert on purpose: Double(sum) / count.
Overflow stops the program. Every integer type has a range: an Int8 goes from −128 to 127. If
an operation goes out of range, Swift doesn't wrap around silently: it stops the program.
The usual mistake: adding when the value is already at its maximum.
Overflow.swift
var level = Int8.maxlevel += 1print(level)
It compiles, and when you run it the program crashes. The crash report says which thread it
happened on (a thread is a sequence of instructions the processor executes; this program has just
one):
Thread 0 "Overflow" crashed:
On Linux, with Swift 6.4.2, this crash doesn't come with a Swift message: the report describes it
as "System trap". Better to stop than to carry on with a level of −128 that nobody wanted.
Going deeper
wrapping around on purpose, and when the compiler catches it. For a hash (I
define it in "Collections") or for modular arithmetic (clock arithmetic, where 1 comes after
12), you do want to wrap around. You ask for it with an overflow operator: &+, &-, or &*
do the operation and throw away whatever doesn't fit; that's why top &+ 1 gives −128. If the
compiler can work out the addition while compiling, the error arrives before you run anything:
OverflowConstant.swift
func nextLevel() -> Int8 { let top = Int8.max return top + 1}print(nextLevel())
errores/OverflowConstant.swift:3:16: error: arithmetic operation '127 + 1' (on type 'Int8') results in an overflow1 | func nextLevel() -> Int8 {2 | let top = Int8.max3 | return top + 1 | `- error: arithmetic operation '127 + 1' (on type 'Int8') results in an overflow4 | }5 | print(nextLevel())
It's a best-effort check, not a rule: the same addition at the top level of a file compiles and
stops when it runs. And the crash is the default, not a law of physics: the -Ounchecked
optimization level removes that check, among others. With swiftc -swift-version 6 -Ounchecked,
the same Overflow.swift prints:
-128
Going deeper
ranges, text, and other languages. 1...3 is a closed range (it includes the
3) and 1..<3 a half-open one (it doesn't). A Character is what a person sees as one letter:
the "é" in the example is an e followed by an accent that combines with it, two Unicode
scalars and one character; that's why count gives 1 and unicodeScalars.count gives 2.
Counting characters means walking through the text, and that's why a String can't be indexed
with an integer like text[3]. Java, by contrast, converts an int to a double without being
asked (a widening conversion), and its int wraps around silently on overflow unless you use
Math.addExact. In TypeScript, as in JavaScript, almost every number is a number, a
double-precision binary floating-point value (IEEE 754), with no separate integer type; for
large integers there's bigint.
What to take away: in Swift, numbers don't change type on their own and don't overflow
silently.
Check what you learned. What does print(Int8.max &+ 1) print? And what happens if you remove
the &?
Solution
it prints -128: &+ wraps around on purpose. Without the &, the program stops
when it runs the addition; if the compiler can work it out earlier, as in OverflowConstant.swift,
it doesn't even compile.
Collections
If you pass your task list to a function and the function adds one, did your list change? In Swift,
no. Swift ships three collections:
Collection
What it holds
Use it when
Array ([Int])
values in order, duplicates allowed
order matters or you access by position
Dictionary ([String: Int])
key → value pairs, no repeated keys
you look a value up by its key
Set (Set<String>)
unique values with no order
all that matters is whether something is there
A Set stores each value only once and answers "is this value here?" quickly, but it keeps no
order. To decide where each element goes, it uses its hash, a number computed from the value. A
Dictionary associates each key with a value.
CollectionsValue.swift
let original = [1, 2, 3]var copy = original // assigning copies the valuecopy.append(4) // only the copy changesprint("original:", original)print("copy:", copy)print("first:", original[0], "count:", copy.count)var tags: Set<String> = ["swift", "ios"]tags.insert("swift") // already there: a Set keeps one of eachprint("tags:", tags.sorted(), "contains ios:", tags.contains("ios"))
Look at the first two lines of the output: copy has a 4 and original doesn't. All three
collections have value semantics: assigning one to another variable, or passing it to a
function, behaves like an independent copy. Whatever you do to the copy doesn't change the original,
and whatever you do to the original doesn't change the copy.
Why does it matter? Because nobody changes an array behind your back. If a function receives your
list, you can reason about your code by looking only at your code: the function works on its copy.
In languages where lists are shared by reference, an append somewhere else in the program can
change what you're iterating over.
The rest of the example: original[0] reads by position (indices start at 0), count says how many
elements there are, insert adds to a Set (if the value was already there, nothing changes), and
contains asks whether a value is present. To print the set, the example uses sorted(), which
returns a sorted array. It's not about looks: it's the only way the output stays the same on every
run.
Copying Doesn't Always Cost a Copy
If every assignment copied every element, passing an array with a million elements to a function
would be very expensive. The standard library (the code that ships with Swift: Array, String,
print…) avoids that with copy-on-write: on assignment, both variables share the same element
storage (a buffer), and the real copy happens only when one of them is modified. Step
through it:
Copying an array: what you see and what the library does today
a
buffer [1, 2, 3] (done)
let a
b
buffer [1, 2, 3, 4] (done)
var b
Storage
Step 4 of 4
Step 4 of 4: Copying only at step 3 is documented behavior of Array, not a language guarantee. What is guaranteed is that it always behaves as if it had been copied at step 2.
let a = [1, 2, 3] creates storage with three elements, and a uses it.
var b = a. Your code already sees two independent values, but for now both use the same storage: nothing was copied.
b.append(4). b is about to modify shared storage, so the copy happens first and then the 4 is added. a still holds [1, 2, 3].
Copying only at step 3 is documented behavior of Array, not a language guarantee. What is guaranteed is that it always behaves as if it had been copied at step 2.
The last step is the part people get wrong most often in interviews, and the one you need to be able
to explain. For cost, the Array documentation says the first modification of a shared copy pays
for the copy, and that sometimes it copies even less. A type you write yourself doesn't get it for free: you'll see that in the Going
deeper box of "Structs and Classes".
Counting with a Dictionary
The most common use of a dictionary is counting. This program counts how many tasks carry each tag:
Frequencies.swift
let tags = ["home", "work", "home", "errands", "home", "work"]var counts: [String: Int] = [:]for tag in tags { counts[tag, default: 0] += 1 // starts at 0 the first time a tag shows up}for tag in counts.keys.sorted() { // sorted: a Dictionary has no order you can rely on print(tag, counts[tag, default: 0])}
errands 1home 3work 2
for tag in tags walks the array one element at a time (I explain loops in the next section).
counts[tag, default: 0] += 1 reads that tag's count or, if it isn't there yet, starts from 0, and
adds 1. Without default:, reading a key returns "a value or none", because the key may not exist:
that kind of data is called an optional, and I explain it in "Optionals".
The usual mistake: printing a dictionary or a set as is and taking the order for granted. A
Dictionary's order is stable as long as you don't modify it, and unpredictable otherwise; a Set
has no defined order. On top of that, the hash value that decides where each element lands is
computed with a random seed (the starting number of the calculation) that usually changes on
every run of the program. Not even within one
run is there a guarantee: two equal sets can iterate in a different order.
SetOrder.swift
var small: Set<Int> = []var roomy = Set<Int>(minimumCapacity: 200) // the same values, more room reservedfor number in 0..<20 { small.insert(number) roomy.insert(number)}print("equal:", small == roomy)print("same order:", Array(small) == Array(roomy))
equal: truesame order: false
If order matters, sort: counts.keys.sorted(). And never save to disk, or compare, the order of a
Set or a Dictionary.
Check what you learned. After let a = [1, 2, 3], var b = a, and b.append(4), how many
elements does a have?
Solution
three. Arrays have value semantics: b behaves like an independent copy from the
moment it's assigned, and its append doesn't touch a.
What to take away: a collection you assigned is yours; its order, unless you ask for one,
isn't.
Going deeper
the difference between guarantee and implementation has two recent
confirmations. Swift 6.4 ships UniqueArray, an array with a single owner (it isn't copied) that
for that reason also accepts elements that can't be copied; it works without the copy-on-write
allocations you'd see with Array. And Hasher, the type that computes hashes, "usually" uses a different random seed on every run,
with an algorithm that may change between versions: that's why an element's hash value is never
saved or sent to another process (another running program).
Control Flow
What does your code do when a response code shows up that you didn't plan for? In Swift, if you
didn't think about it, it doesn't compile. First, the familiar part: loops and conditions look like
the ones in other languages.
Loops.swift
for step in 1...3 { print("for:", step)}var remaining = 2while remaining > 0 { // checks first: may run zero times print("while:", remaining) remaining -= 1}var attempts = 0repeat { // runs once, then checks attempts += 1} while attempts < 3print("repeat ran", attempts, "times")for temperature in [31, 20, 5] { if temperature > 30 { print(temperature, "hot") } else if temperature > 15 { print(temperature, "mild") } else { print(temperature, "cold") }}
for … in walks a range or a collection. while checks the condition before each pass, so it may
never run; repeat … while checks it afterwards, so it runs at least once. if, else if, and
else pick a branch. An if condition has to be a Bool: Swift doesn't accept a number as a
condition the way C does.
switch Without Gaps
Swift's switch is stricter and more powerful than the one in C or classic Java. Stricter, because
it's an exhaustive switch: the compiler requires it to cover every possible value of the type.
More powerful, because each case is a pattern, not just a value:
SwitchPatterns.swift
func describe(_ point: (Int, Int)) -> String { switch point { case (0, 0): return "origin" case (_, 0): return "on the x axis" case (0, _): return "on the y axis" case let (x, y) where x == y: return "on the diagonal" case (-5...5, -5...5): return "near the origin" default: return "far away" }}for point in [(0, 0), (3, 0), (2, 2), (1, 4), (9, -9)] { print(point, "->", describe(point))}
(0, 0) -> origin(3, 0) -> on the x axis(2, 2) -> on the diagonal(1, 4) -> near the origin(9, -9) -> far away
point is a tuple, a pair of values written in parentheses. Read the cases like this:
(0, 0) matches only the origin.
(_, 0): the _ means "any value"; it matches every point whose y is 0.
case let (x, y) where x == y names both values and adds a condition with where.
(-5...5, -5...5) uses ranges: it matches if each coordinate is between −5 and 5.
default covers everything else. Over an Int you need it, because there are a huge number of
possible integers.
A case can also list several patterns separated by commas (case 200, 204:), and if a case should
do nothing, its body is break.
describe is a function, which I explain in the next section; for now it's enough to read it as
taking a point and returning a piece of text. Two details set Swift apart from C: each case ends when
its body ends, with no break, and there's no implicit fall-through to the next case. If you ever
want one, you ask for it with fallthrough.
The usual mistake: a switch over an integer with no default.
errores/SwitchNotExhaustive.swift:2:1: error: switch must be exhaustive1 | let code = 4042 | switch code { | |- error: switch must be exhaustive | `- note: add a default clause3 | case 200:4 | print("ok")
That this is an error, and not a slip that reaches production, is the whole point of the exhaustive
switch. In "Enumerations" you'll see it really pay off: with a type that has only a few cases, the
compiler flags every switch when you add a new one.
If you come from Java. Java's classic switch falls through to the next case if you forget the
break. The arrow form (Java 14 and later) doesn't fall through, and a switch used as an
expression has to be exhaustive. Swift's resembles the second one, and it requires exhaustiveness
every time.
guard: The Happy Path Without Nesting
guard checks a condition and, if it doesn't hold, forces you to leave:
A guard's else has to leave the scope it's in, the block of braces it belongs to (with
return, break, continue, by throwing an error, or by calling a function that never returns);
otherwise the code doesn't compile. That's why, below each guard, the condition is guaranteed and
the normal-case code stays unnested, at the left margin. Use it at the top of a function to rule out
what's invalid; use if when both branches are equally normal.
"cost: \(cost)" is string interpolation: \(…) inside a string inserts the value of what's in
the parentheses. You'll see it in almost every example.
What to take away: a Swift switch covers every case or doesn't compile; guard clears the happy path.
Check what you learned. What does fallthrough do inside a case?
Solution
it explicitly moves on to the body of the next case, without checking its pattern.
In Swift no case falls through on its own: fallthrough is how you ask for it.
Functions
Note: good place for a break: you're about a fifth of the way through the guide, some 30
minutes of reading.
In Swift, a well-written call reads almost like a sentence: move(from: 3, to: 10).
Functions.swift
func move(from start: Int, to end: Int) -> Int { // labels: from, to; names: start, end return end - start}func greet(_ name: String, punctuation: String = "!") -> String { // _ drops the label return "Hello, " + name + punctuation}func average(_ numbers: Double...) -> Double { // variadic: arrives as [Double] var sum = 0.0 for number in numbers { sum += number } return sum / Double(numbers.count)}func double(_ value: inout Int) { // copied in, then copied back out value *= 2}func square(_ x: Int) -> Int { x * x } // one expression: return is implicitprint(move(from: 3, to: 10))print(greet("Ana"), greet("Luis", punctuation: "?"))print(average(2, 4, 9))var score = 21double(&score)print("score:", score)let operation: (Int, Int) -> Int = move // a function is a valueprint(operation(1, 5), square(4))
7Hello, Ana! Hello, Luis?5.0score: 424 16
A function is declared with func, its name, its parameters in parentheses, and, after ->, the
type it returns. All of that together (name, parameters, and return type) is its signature. What's
distinctly Swift is in the parameters.
Labels. In move(from start: Int, to end: Int), each parameter has two names. The
argument label (from, to) is what the caller writes: move(from: 3, to: 10). The parameter name
(start, end) is what the function body uses. If you write a single name, it serves both
purposes; if the label is _, the call leaves it out, as in greet("Ana"). The goal is for the call
to read well at the call site, which is where it's read most often.
Default values.punctuation: String = "!" makes that argument optional at the call.
Variadics.Double... accepts any number of values, and inside the function they arrive as an
array (numbers).
Constant parameters and inout. A function's parameters are constants: you can't reassign them.
If a function needs to change the caller's value, the parameter is marked inout and the call says
so with &: double(&score). The model the language defines is copy-in copy-out: the value comes
in copied, the function works on its copy and, when it finishes, the result is copied back into the
original variable.
Functions as values. A function has a type, such as (Int, Int) -> Int, and can be stored in a
constant and called later: operation(1, 5). And if the body is a single expression, as in
square, the return is implicit.
The usual mistake: calling an inout function without the &.
errores/InoutWithoutAmpersand.swift:6:8: error: passing value of type 'Int' to an inout parameter requires explicit '&'4 |5 | var score = 216 | double(score) | `- error: passing value of type 'Int' to an inout parameter requires explicit '&'7 |
The & isn't a syntax detail: it warns whoever reads the call that the variable may come out
changed.
While a call with inout lasts, nothing else may touch that variable: that's the exclusive
access rule, and the box shows what happens if you break it.
Going deeper
exclusive access, in action. Reading the original variable while the function
is modifying it stops the program. Here, inside demo(), there are two nested functions (declared inside
another function, able to read its variables): addBonus modifies score through value, and
meanwhile currentScore() reads that same score:
ExclusiveAccess.swift
func demo() { var score = 10 func currentScore() -> Int { return score } func addBonus(_ value: inout Int) { value += currentScore() } addBonus(&score) print(score)}demo()
It compiles, and when it runs Swift detects the conflict and stops the program:
Simultaneous accesses to 0x…, but modification requires exclusive access.Previous access (a modification) started at ExclusiveAccess`<unavailable> + N (0x…).Current access (a read) started at:Fatal access conflict detected.
The memory addresses (0x…) and the offset (+ N) change on every run, so they appear here
without digits: your terminal shows real numbers.
"Simultaneous accesses… requires exclusive access": two accesses at once, and a modification
requires exclusivity. The fix is to read the value before the call, into a constant. This rule is
the foundation of the data-race safety you'll see in part 2.
What to take away: labels make the call read well; inout is marked with & and is exclusive while it lasts.
Check what you learned. Is inout pass-by-reference?
Solution
the language's model is copy-in copy-out. The compiler may implement it by passing a
reference, as an optimization, but your code shouldn't depend on that. And while the function
runs, nothing else may touch the original variable: that's the exclusive access rule from
above.
Closures
Sorting a task list by title, getting notified when a download finishes, reacting to a tap: in
Swift, all of that is written by passing a block of code as a value.
A closure is a block of code you can pass around as a value, like a function without a name, and
that captures its context: it can use the variables from the place where it was written, even after
that place has finished running. The functions from the previous section are a special case of
closure, one with a name.
ClosuresCapture.swift
let names = ["Luis", "Ana", "Marta"]let long = names.sorted(by: { (a: String, b: String) -> Bool in return a < b})let short = names.sorted(by: { $0 < $1 }) // types inferred, shorthand argument nameslet trailing = names.sorted { $0 < $1 } // trailing closure: after the parenthesesprint(long)print(short == long, trailing == long)func makeCounter() -> () -> Int { var count = 0 return { count += 1 // uses count itself, not a copy of it return count }}let counter = makeCounter()print(counter(), counter(), counter())
["Ana", "Luis", "Marta"]true true1 2 3
From the Long Form to the Short One
sorted(by:) sorts an array and takes a closure that says whether one element goes before another.
The three calls in the example do the same thing, each one shorter:
Long form:{ (a: String, b: String) -> Bool in return a < b }. Inside the braces, the
parameters and the return type, the word in, and the body.
Inferred types and shorthand names: the compiler already knows it compares two Strings, so
you can drop the types and use $0 and $1 for the first and second arguments. With a single
expression, the return goes too.
Trailing closure: when the closure is the last argument, you write it after the parentheses
and without its label: names.sorted { $0 < $1 }. It's the form you'll see all over SwiftUI code.
Use $0 in one-line closures. If the body grows, give the parameters names: $0 on the fifth line
of a closure makes the reader count.
Transforming Collections: map, filter, and Friends
sorted(by:) is one of several collection functions that take a closure. With four more you can
replace most of the loops you'd otherwise write by hand:
HigherOrder.swift
let titles = ["Buy milk", "Call Ana", "Pay rent", "Buy bread"]let shopping = titles.filter { $0.hasPrefix("Buy") } // keeps the elements that pass the testlet lengths = titles.map { $0.count } // transforms every elementlet firstTwo = titles.prefix(2) // the first two, or fewer if there aren'tlet minutes = [15, 30, 10].reduce(0, +) // combines all into one value: 0 + 15 + 30 + 10print(shopping)print(lengths)print(firstTwo)print("minutes:", minutes)let counts = ["home": 3, "work": 2, "errands": 1]let ranked = counts.sorted { $0.value > $1.value } // a Dictionary sorts into (key, value) pairsfor pair in ranked { print(pair.key, pair.value)}let best: (tag: String, count: Int) = (tag: "home", count: 3) // a tuple with named elementsprint(best.tag, best.count)
filter keeps the elements for which the closure returns true.
map transforms each element and returns a new array with the results, in the same order.
prefix(2) takes the first two (or fewer, if there aren't that many).
reduce(0, +) combines them all into a single value: it starts at 0 and adds each element. The +
is an operator, and in Swift an operator is also a function you can pass around.
The last lines sort a dictionary: sorted on a Dictionary gives an array of pairs, each with
its key and its value, and the closure decides the order (here, highest value first). A pair
like that is a tuple, like the point in "Control Flow"; and a
tuple can name each element, as in best.tag and best.count.
None of them modifies the original array: they return a new one. Use them when the code says what
you want ("the ones that start with Buy"); a for is still better when the body has several steps or
side effects, such as printing and accumulating at once. In "Optionals" you'll see one more,
compactMap.
Capturing Keeps the Variable, Not Its Value
makeCounter() declares a variable count and returns a closure that increments it. When
makeCounter returns, count should disappear, but the closure captured it: it keeps it alive and
keeps modifying it. That's why counter() returns 1, 2, and 3.
The closure captures the variable itself, not a copy of its value at the moment it was created.
And closures are reference types: if you store the same closure in two constants, both share what it
captured.
The usual mistake: believing a closure "snapshots" the value when it's created.
CaptureList.swift
var level = 1let withoutList = { print("without list:", level) } // reads level when it runslet withList = { [level] in print("with list:", level) } // copies level nowlevel = 2withoutList()withList()
without list: 2with list: 1
withoutList reads level when it runs, and by then it's 2. If you want the value from the moment
it was created, you ask for it with a capture list: [level] in copies level when the closure
is created. Capture lists come back in "ARC", for a different purpose.
One last rule, which you'll need in "ARC": if a function stores the closure it receives so it can run
it later, the parameter is marked @escaping: the closure stays alive after the call, together
with everything it captured. Without the attribute, the compiler won't let you store it. The details
are in the box.
Going deeper
@escaping in practice. This function stores each closure in an array it takes
as inout, to run them later:
Escaping.swift
func register(_ handler: @escaping () -> Void, in handlers: inout [() -> Void]) { handlers.append(handler) // kept for later: it escapes register}var handlers: [() -> Void] = []register({ print("first handler") }, in: &handlers)register({ print("second handler") }, in: &handlers)for handler in handlers { handler() // runs after register has returned}
first handlersecond handler
Without the attribute, storing it doesn't compile:
errores/Escaping.swift:2:21: error: converting non-escaping parameter 'handler' to generic parameter 'Element' may allow it to escape1 | func register(_ handler: () -> Void, in handlers: inout [() -> Void]) {2 | handlers.append(handler) | `- error: converting non-escaping parameter 'handler' to generic parameter 'Element' may allow it to escape3 | }4 |
The message talks about a "generic parameter Element": that's the type of the array's elements
(generics get their own section later on). What matters is the second half: storing it "may allow
it to escape". A non-escaping closure ends with the call, so it can't keep anything alive afterwards;
an escaping one can. On iOS, what it captures often includes an object from your user interface,
and that's where the retain cycles in "ARC" come from.
If you come from JavaScript. JavaScript closures also capture the variable and not a copy of its
value: the level example behaves the same with an arrow function. What JavaScript doesn't have is
the @escaping attribute or the capture list.
What to take away: a closure keeps the variable it captures, not a snapshot of its value.
Check what you learned. If you call makeCounter() twice and store the results in first and
second, what does print(first(), first(), second()) print?
Solution
each call to makeCounter() creates its own count variable, and each closure
captures its own:
TwoCounters.swift
let first = makeCounter()let second = makeCounter()print(first(), first(), second())
1 2 1
Optionals
What does Int("forty-two") return? Nothing, and Swift makes you say so in the type.
Many operations may have no result: turning "forty-two" into a number, looking up a key that isn't
in a dictionary, asking for the first element of an empty array. An optional is a type that
says, in the type itself, "there's a value here, or there's none". It's written with ?: Int? is
"an Int or nothing", and nothing is written nil.
Why They Exist
In Java, any variable of an object type can be null, and the compiler doesn't force you to check:
String s = null; s.length() compiles and fails at runtime with a NullPointerException. In Swift,
a String? isn't a String, and the compiler won't let you use it as if it were:
The usual mistake: using an optional as if it were the value.
OptionalNotUnwrapped.swift
let parsed = Int("42")let doubled = parsed * 2
errores/OptionalNotUnwrapped.swift:2:15: error: value of optional type 'Int?' must be unwrapped to a value of type 'Int'1 | let parsed = Int("42")2 | let doubled = parsed * 2 | |- error: value of optional type 'Int?' must be unwrapped to a value of type 'Int' | |- note: coalesce using '??' to provide a default when the optional value contains 'nil' | `- note: force-unwrap using '!' to abort execution if the optional value contains 'nil'3 |
Int("42") returns Int?, because the conversion can fail with other text. The compiler makes you
decide what to do if there's no number, and the two notes suggest two ways. The first one, with
??, is the safe one.
The failure moves from runtime (on someone's phone) to compile time (on your Mac). If you come from
TypeScript with strictNullChecks, the idea will feel familiar: there, too, absence lives in the type
(string | undefined). The sharp contrast is with Java, where absence isn't in the type and
Optional<T> is a library class, meant mainly as the return type of a method (a function that
belongs to a type), not a rule of the language.
Four Ways to Unwrap
Unwrapping an optional means getting the value out of it, if there is one.
Optionals.swift
let parsed: Int? = Int("42") // Int(_:) can fail, so it returns Int?if let parsed { // 1. if let: use the value only if there is one print("if let:", parsed)}func doubled(_ text: String) -> Int { guard let number = Int(text) else { // 2. guard let: leave early if there is none return 0 } return number * 2}print("guard let:", doubled("21"), doubled("x"))let missing: Int? = nilprint("??:", missing ?? 0) // 3. ??: a default of the wrapped typelet words = ["Swift", "Kotlin"] // 4. optional chaining: each ?. may stop at nillet firstIsUpper = words.first?.first?.isUppercaseprint("chaining:", firstIsUpper ?? false)let counts = ["red": 3]print("dictionary:", counts["red"] ?? 0, counts["blue"] ?? 0) // a key may be missing
if let: 42guard let: 42 0??: 0chaining: truedictionary: 3 0
if let runs the block only if there's a value, and inside the block parsed is already an
Int. if let parsed is the short form (since Swift 5.7) of if let parsed = parsed: the name
inside shadows the optional outside.
guard let is the same thing flipped: if there's no value, it leaves; if there is, the value
stays available for the rest of the function. It's the guard from "Control Flow", applied to an
optional. In a guard or an if, commas separate conditions that must all hold, and any of
them can be a let: guard let number = Int(text), number > 0 else { return 0 }.
?? (nil coalescing) gives a default value if there's nothing. The default has to be of the
wrapped type: with an Int?, an Int.
Optional chaining (?.) calls something on an optional: if there's a value, it continues; if
it's nil, the whole chain gives nil. words.first is a String? (the array could be empty)
and .first on a string is a Character? (the string could be empty). The result of a chain with
?. is always optional, even if the last property (a value that belongs to another one,
like an array's count) isn't: here, isUppercase is a Bool, but
firstIsUpper is a Bool?.
The last line goes back to "Collections": reading a dictionary with a key that doesn't exist gives
nil, which is why a dictionary's subscript returns an optional.
Optionals bring in the last collection function I promised you in "Closures": compactMap
transforms like map, but drops the nil results:
CompactMap.swift
let estimates = ["15", "soon", "30", ""]let parsed = estimates.map { Int($0) } // [Int?]: one optional per textlet valid = estimates.compactMap { Int($0) } // [Int]: the values, without the empty onesprint(parsed)print(valid)
[Optional(15), nil, Optional(30), nil][15, 30]
With map, each string gives an Int? and the array keeps the empty ones; with compactMap, only
the numbers remain. Look at how Swift prints an optional: Optional(15).
An Optional Is an Enum with Two Cases
Int? is shorthand for Optional<Int>, and Optional is an ordinary enumeration from the standard
library with two cases: .none, which is the same as nil, and .some(Wrapped), which carries the
value inside. Enumerations have their own section, "Enumerations"; for now it's enough to read it as
"one of two cases". Since it's an enum, you can go through it with switch:
OptionalIsEnum.swift
let present: Optional<Int> = .some(5) // the long spelling of Int?let absent: Int? = .none // .none is the same as nilfor value in [present, absent] { switch value { case .some(let number): print("case .some:", number) case .none: print("case .none") }}print(present == 5, absent == nil)
case .some: 5case .nonetrue true
Force-Unwrapping with !
parsed! says "I know there's a value here; if there isn't, stop the program". If you're wrong:
ForceUnwrapNil.swift
let parsed = Int("forty-two")print(parsed! * 2)
ForceUnwrapNil/ForceUnwrapNil.swift:2: Fatal error: Unexpectedly found nil while unwrapping an Optional value
That's an app crash on someone's phone. When is ! acceptable? Only when a nil would be a
programming error you'd rather discover with an immediate crash than with a strange state later on.
The typical case is a resource your own compilation puts into the app (I explain it in "Resources"): if
it's missing, the app was built wrong and there's no reasonable way to carry on. For data that comes
from outside (what a person types, what a server responds), never: there, nil is a normal case and
you handle it.
There's a variant, T! (an implicitly unwrapped optional), which is an ordinary optional that the
compiler force-unwraps whenever it can't use it as an optional. Don't use it for values that can
become nil again.
What to take away: absence lives in the type; unwrap with if let, guard let, or ??, and keep ! for programmer errors.
Check what you learned. If person is of type Person? and address.street is a String, what
type is person?.address.street?
Solution
String?. The result of optional chaining is always optional: if person is nil,
there's no street to return.
Going deeper
since Optional is an enum from the standard library and not compiler magic, it
has methods of its own: map transforms the value if there is one (parsed.map { $0 * 2 } gives
an Int?) and flatMap chains a transformation that also returns an optional. The language's
sugar (?, if let, ??, ?.) rests on that type. And T! isn't a separate type: it's an
Optional with a marker that asks the compiler to force it wherever a T is needed.
Structs and Classes
A task that two screens show at the same time: if one marks it as done, does the other find out? The
answer depends on the most important decision when you model data in Swift: whether a type is copied
or shared.
Swift has two ways to define a type with properties and methods. A struct (structure) is a value
type: assigning it or passing it creates an independent copy, as with arrays. A class (class) is a
reference type: assigning it copies a reference, and both variables point to the same object in
memory.
ValueVsReference.swift
struct PointValue { var x: Int}final class PointObject { var x: Int init(x: Int) { // a class writes its own initializer self.x = x }}var a = PointValue(x: 1) // a struct gets a memberwise initializer for freevar b = a // b is a copyb.x = 99print("struct:", a.x, b.x)let c = PointObject(x: 1)let d = c // d is a second reference to the same objectd.x = 99print("class:", c.x, d.x, c === d)struct Wallet { var balance = 0 mutating func deposit(_ amount: Int) { // mutating: this method changes the struct balance += amount }}var wallet = Wallet()wallet.deposit(30)print("wallet:", wallet.balance)
struct: 1 99class: 99 99 truewallet: 30
Walk through it:
PointValue is a struct. var b = a copies: changing b.x doesn't touch a.x. PointValue(x: 1)
creates one; where that way of creating it comes from, you'll see in "Initializers".
PointObject is a class, with its init written by hand. An instance is a concrete value created from a type, and inside the type self is the
instance you're working with: self.x = x assigns the
parameter x to this instance's x property. let d = c doesn't create another object: d is
another reference to the same one, and d.x = 99 is visible through c. The === operator
compares identity: whether two references point to the same object.
final in front of class prevents another class from inheriting from this one (taking it as a
base and adding or changing behavior). Use it by default: inheritance is a design decision worth
making on purpose.
A struct method that modifies the struct itself is marked mutating. That way, whoever reads the
call wallet.deposit(30) knows wallet has to be a var.
A struct is copied; a class is shared; and a struct that holds a reference copies the reference, not the object.
let with a Class
With a struct, let freezes the whole value: no property changes. With a class, let fixes the
reference (the variable can't point to another object), but the object can still be modified:
LetWithClass.swift
final class Settings { var volume = 5}let settings = Settings()settings.volume = 8 // allowed: let fixes the reference, not the objectprint("volume:", settings.volume)
errores/LetStructProperty.swift:6:10: error: cannot assign to property: 'settings' is a 'let' constant3 | }4 |5 | let settings = Settings() | `- note: change 'let' to 'var' to make it mutable6 | settings.volume = 8 | `- error: cannot assign to property: 'settings' is a 'let' constant7 |
This is the comparison with JavaScript's const I left pending in "Constants, Variables, and
Initialization": a let holding a class instance fixes the reference and not the object, just like a
const holding an object. They aren't identical: a const requires its value in the same
declaration, and a Swift let can receive it later, as you saw with let total: Int.
A Struct That Holds a Reference
What if a struct has a class inside it? Before looking at the output, try to predict it:
StructWithReference.swift
final class Counter { var value = 0}struct Panel { var title: String let counter: Counter // a reference stored inside a value}var original = Panel(title: "Original", counter: Counter())var copy = original // the struct is copied...copy.title = "Copy" // ...so its String is independentcopy.counter.value += 1 // but both copies point to the SAME Counterprint(original.title, original.counter.value)print(copy.title, copy.counter.value)print(original.counter === copy.counter)
Original 1Copy 1true
var copy = original copies the struct, and its properties along with it. title is a String, a
value type: the copy has its own. But counter is a reference, and copying a reference gives you
another reference to the same object. Both copies of the struct share the same Counter, as the
true on the last line shows.
The general rule: a struct has value semantics only if everything it holds has them too. A struct
with a mutable class inside promises something it doesn't deliver, and it's a classic source of
hard-to-find bugs.
Initializers
An initializer (init) prepares a new instance: it gives all of its stored properties a value
before anyone uses it. It's the definite initialization from the first section, applied to a type.
Initializers.swift
struct TaskItem { var title: String var isDone = false // a default value: the memberwise initializer can skip it}let milk = TaskItem(title: "Buy milk")let rent = TaskItem(title: "Pay rent", isDone: true)print(milk.title, milk.isDone, "|", rent.title, rent.isDone)struct Estimate { let minutes: Int init?(minutes: Int) { // init?: a failable initializer, it can return nil guard minutes > 0 else { return nil } self.minutes = minutes // self: the value being initialized }}print(Estimate(minutes: 30)?.minutes ?? 0, Estimate(minutes: -5) == nil)final class Reminder { let title: String var minutesBefore: Int init(title: String, minutesBefore: Int) { // gives every stored property a value self.title = title self.minutesBefore = minutesBefore } convenience init(title: String) { // a shortcut that must call the main init self.init(title: title, minutesBefore: 10) }}print(Reminder(title: "Dentist").minutesBefore)
Buy milk false | Pay rent true30 true10
A struct gets a memberwise initializer for free, with its properties in order; the ones with a
default value, like isDone, can be left out when you call it.
init? is a failable initializer: it returns an optional, and return nil says "with this data
there's no instance". That's how Int("42") works.
A class gets no memberwise initializer: it writes its own, which has to give every stored property
a value. A convenience init is a shortcut that ends up calling another initializer of the same
class with self.init(…). Inheritance brings more rules (each class initializes its own part
before calling the superclass); with final classes, as in this series, you don't need them.
Computed Properties, Observers, and static
Properties.swift
struct TaskList { private(set) var titles: [String] = [] // anyone can read it; only TaskList can change it static let maxCount = 3 // static: belongs to the type, not to each list var filter = "" { didSet { // an observer: runs after every change print("filter: \"\(oldValue)\" -> \"\(filter)\"") } } var count: Int { // computed: calculated on every read, not stored titles.count } mutating func add(_ title: String) { guard titles.count < TaskList.maxCount else { return } titles.append(title) }}var list = TaskList()list.add("Buy milk")list.add("Call Ana")list.filter = "Buy"print(list.count, "of", TaskList.maxCount, list.titles)
filter: "" -> "Buy"2 of 3 ["Buy milk", "Call Ana"]
A computed property (count) stores nothing: it calculates its value every time you read it.
An observer (didSet) is code that runs after every change to a stored property; inside it,
oldValue is the previous value. willSet runs before.
static declares something that belongs to the type, not to each instance: TaskList.maxCount is
a single value for all lists.
Who Can Touch What: Access Control
private(set) on titles is access control: it says what code can use each declaration. Outside
TaskList you can read titles, but you can't modify it:
PrivateSetter.swift
struct TaskList { private(set) var titles: [String] = []}var list = TaskList()list.titles.append("Buy milk")
errores/PrivateSetter.swift:6:13: error: cannot use mutating member on immutable value: 'titles' setter is inaccessible4 |5 | var list = TaskList()6 | list.titles.append("Buy milk") | `- error: cannot use mutating member on immutable value: 'titles' setter is inaccessible7 |
The levels go from most closed to most open. The last three matter when you split an app into
several modules: a module is a unit that's compiled together. Your app is one, and each target of
a package (Swift code distributed together, with its own list of modules) and each framework you
bring in with import is another.
Level
Who sees it
private
the type that declares it (and its extensions, which you'll see in "Protocols and Extensions", in the same file)
fileprivate
the whole file
internal
the whole module: it's the default level if you write nothing
package
every module in the same Swift package
public
other modules that import yours, too
open
like public, and other modules can also subclass the class and override its methods
The practical rule: every property that holds state starts as private or
private(set), and opens up only if other code needs it. That way, the only way to change titles
is add(_:), which respects the maximum.
Which One to Choose
Struct by default for data models: a task, a user, a network response. Something nobody else
can change is easier to reason about.
Class when you need shared identity (several parts of the app see and modify the same
object) or a life of its own, with a moment when the object is freed and can do something as it
goes. I explain that last part in "ARC".
If you come from Java. Java's records aren't value types: they're classes with final fields,
and assigning a record to another variable copies the reference. The closest thing in Java to a
Swift struct is a record whose fields are immutable types, and even then it's shared.
What to take away: struct by default; a class when you really need sharing.
Check what you learned. In StructWithReference.swift, what would change in the output if
Counter were a struct and counter a var?
Solution
the copy would have its own counter. copy.counter.value += 1 would change only
copy's: the output would be Original 0, Copy 1, and the === line would no longer compile,
because === only compares class references. It's the same fix interview exercise 4 applies, where
you do see it run.
Going deeper
a struct of your own doesn't get copy-on-write for free: if it keeps its storage
in a class, the copy shares that storage, as you've just seen. To have value semantics and cheap
copies at the same time, the standard library offers isKnownUniquelyReferenced, which tells you
whether a reference is the only one pointing to its object. This is how you implement it by hand:
CopyOnWrite.swift
final class Storage { var values: [Int] init(_ values: [Int]) { self.values = values }}struct Numbers { private var storage: Storage // private: only Numbers can touch it init(_ values: [Int]) { storage = Storage(values) } var values: [Int] { storage.values } mutating func append(_ value: Int) { if isKnownUniquelyReferenced(&storage) { print("deep copy: no") } else { print("deep copy: yes") // shared with another copy: copy before writing storage = Storage(storage.values) } storage.values.append(value) }}var a = Numbers([1, 2])a.append(3) // only a uses the storagevar b = a // now a and b share itb.append(4)print("a:", a.values, "b:", b.values)
The first append finds the storage unshared and writes straight to it. After var b = a there
are two references, so the second one copies before writing. Here the decision is made by your
code, not by the library. private (you saw it above, in "Who Can Touch What") prevents other code
from touching storage and breaking the promise.
Enumerations
A screen that loads tasks is loading, or it already has them, or it failed. Never two things at
once. A type can make anything else impossible to write.
An enumeration (enum) is a type with a closed set of cases. Unlike C enums, each case can carry
associated values of any type: the data that belongs to that case.
EnumState.swift
enum LoadState { case loading case loaded([String]) // an associated value: the items case failed(String) // an associated value: the reason}func message(for state: LoadState) -> String { switch state { // no default: every case is listed case .loading: return "Loading..." case .loaded(let items): return "\(items.count) items" case .failed(let reason): return "Error: \(reason)" }}let states: [LoadState] = [.loading, .loaded(["milk", "bread"]), .failed("offline")]for state in states { print(message(for: state))}
Loading...2 itemsError: offline
.loaded([String]) carries the items; .failed(String), the reason. In the switch,
case .loaded(let items) pulls out the associated value and gives it a name. There's no default:
the switch covers all three cases, so it's exhaustive without one.
Why It Matters: Impossible States You Can't Write
The usual alternative is three loose properties: a Bool that says whether it's loading, an optional
array with the data, and an optional string with the error. Three properties give you eight
combinations, and most of them make no sense: loading and failed at the same time, no data and no
error and not loading. Every view that reads those properties has to guess what to do with the odd
combinations.
With the enum, the type only admits the three real states. You'll meet this idea again
in part 2 and in the part 4 app, where it's called LoadState.
The usual mistake: adding a case and having a default swallow it silently. Without a
default, the compiler takes you to every switch you need to review. If you add .empty to
LoadState:
NewCaseNotHandled.swift
enum LoadState { case loading case loaded([String]) case failed(String) case empty}func message(for state: LoadState) -> String { switch state { case .loading: return "Loading..." case .loaded(let items): return "\(items.count) items" case .failed(let reason): return "Error: \(reason)" }}
errores/NewCaseNotHandled.swift:9:5: error: switch must be exhaustive 7 | 8 | func message(for state: LoadState) -> String { 9 | switch state { | |- error: switch must be exhaustive | `- note: add missing case: '.empty'10 | case .loading:11 | return "Loading..."
With a default: in that switch, the code would compile and .empty would show whatever the
default said, without anyone deciding it.
Raw Values and the List of Cases
An enum can also have a fixed raw value per case, and list all of its cases:
EnumRaw.swift
enum Priority: Int, CaseIterable { case low = 1 case medium // 2: raw values count up from the previous one case high // 3}print(Priority.high.rawValue)print(Priority(rawValue: 2) ?? .low) // from a raw value: may fail, so it's optionalprint(Priority(rawValue: 9) == nil)for priority in Priority.allCases { print(priority, priority.rawValue)}
3mediumtruelow 1medium 2high 3
enum Priority: Int gives each case an integer rawValue; if you only write the first one, the rest
count up from there. Priority(rawValue: 2) builds a case from its raw value, and returns an
optional because the value may not match any case (the 9). CaseIterable is a library protocol
(you'll see protocols in "Protocols and Extensions"): declaring it next to the type gives it
allCases, the list of all its cases in the order they were declared.
If you come from TypeScript. An enum with associated values is equivalent, as a model, to a
discriminated union (a type that is one of several shapes, told apart by a shared field:
{ kind: "loading" } | { kind: "loaded"; items: string[] }). The difference is
exhaustiveness: in Swift the compiler always checks it; in TypeScript it depends on you writing the
check with never.
What to take away: an enum with associated values makes nonsensical states impossible.
Check what you learned. Why is LoadState better than three loose properties,
isLoading: Bool, items: [String]?, and error: String??
Solution
because with three properties you can write combinations that make no sense, such as
loading and failed at the same time, and every reader of the state has to decide what to do with
them. The enum only admits the three real states, and the exhaustive switch forces you to handle
each one.
Going deeper
a case that contains the enum itself (an expression that adds other expressions)
needs indirect, which asks the compiler to store that associated value through a level of
indirection:
EnumIndirect.swift
indirect enum Expression { case number(Int) case sum(Expression, Expression) // a case that contains the enum itself}func evaluate(_ expression: Expression) -> Int { switch expression { case .number(let value): return value case .sum(let left, let right): return evaluate(left) + evaluate(right) }}print(evaluate(.sum(.number(2), .sum(.number(3), .number(4)))))
9
Protocols and Extensions
A function that prints anything with a name (a task, a book, a song) doesn't need to know what type
it receives: it's enough to know what that type can do.
A protocol describes a set of capabilities: properties and methods a type promises to have. A
type adopts the protocol by declaring it and meeting those requirements. An extension
(extension) adds functionality to an existing type, even one you didn't write, such as Int.
ProtocolDefault.swift
protocol Describable { var name: String { get } func describe() -> String // a requirement}extension Describable { func describe() -> String { // the default implementation return "This is \(name)" }}struct Book: Describable { // uses the default let name: String}struct Song: Describable { // brings its own: it wins over the default let name: String func describe() -> String { return "Now playing: \(name)" }}print(Book(name: "The Long Road").describe())print(Song(name: "Blue Morning").describe())extension Int { // an extension also works on types you didn't write var isEven: Bool { self % 2 == 0 }}print(4.isEven, 7.isEven)
This is The Long RoadNow playing: Blue Morningtrue false
Walk through it:
Describable asks for two things: a name property that can be read ({ get }) and a
describe() method. Both are requirements.
extension Describable provides a default implementation of describe(). Every type that adopts
the protocol gets it without writing it.
Book only declares name and uses the default implementation.
Song brings its own describe(). The Swift documentation guarantees that, for a protocol
requirement, the type's implementation takes priority over the default one. That's why
describe() is declared in the protocol and not only in the extension.
extension Int adds a computed property, isEven, to Int. Now 4.isEven works throughout
your module.
What's it good for? Writing code that depends on a capability and not on a concrete type. A function
that takes "something that can describe itself" works with books, songs, and any future type that
adopts Describable. It's the basis of dependency injection (handing an object, from outside, the
pieces it uses, instead of having it create them itself): in part 2 you use it to test code without
the network, by handing it a fake version of the network.
Equality and Hashing for Free
Some library protocols can be adopted for you by the compiler. If a struct declares Equatable (it
can be compared with ==) or Hashable (it can be stored in a Set or used as a dictionary key)
and all of its properties already conform, the compiler synthesizes the implementation: it
compares or combines property by property.
Synthesized.swift
struct TaskItem: Hashable { // Hashable includes Equatable: the compiler writes both var title: String var isDone: Bool}let a = TaskItem(title: "Buy milk", isDone: false)let b = TaskItem(title: "Buy milk", isDone: false)print(a == b) // equal when every stored property is equallet unique: Set<TaskItem> = [a, b, TaskItem(title: "Pay rent", isDone: true)]print(unique.count) // a and b count onceenum Filter { // no associated values: Equatable and Hashable come for free case all, pending, done}print(Filter.pending == .pending, Filter.all == .done)
true2true false
An enum without associated values is Equatable and Hashable without declaring it. That's why
SceneAction, in "The Scene Life Cycle", only writes : Equatable to make it explicit, and nobody
writes its ==. The same mechanism turns a type into JSON (a text format for structured data) and
back, with another library protocol: you'll see it in part 2.
A piece of advice that comes back in the architecture section of part 2: don't create a protocol
with a single implementation "just in case". A protocol earns its place when two types adopt it,
even if one of them is a fake version that only your tests use.
some and any: Two Ways to Use a Protocol as a Type
When a variable, a parameter, or a return value is "something that conforms to Shape", Swift lets
you choose between two forms:
SomeVsAny.swift
protocol Shape { func area() -> Double}struct Square: Shape { let side: Double func area() -> Double { side * side }}struct Rectangle: Shape { let width: Double let height: Double func area() -> Double { width * height }}func makeUnitSquare() -> some Shape { // one concrete type, hidden from the caller return Square(side: 1)}let shapes: [any Shape] = [Square(side: 2), Rectangle(width: 2, height: 3)] // mixed typesvar total = 0.0for shape in shapes { total += shape.area()}print("total:", total)print("unit:", makeUnitSquare().area())
total: 10.0unit: 1.0
some Shape is an opaque type: a concrete type the compiler knows but the caller doesn't
see. makeUnitSquare() always returns a Square; whoever calls it only knows it's a Shape. It's
what you'll see in every SwiftUI view.
any Shape is a box: it can hold any type that conforms to Shape, and switch from one to
another. You need it when you mix different types, as in the shapes array, which holds a
Square and a Rectangle.
The practical rule: use some by default and any when you really need to keep different types in
the same place.
The usual mistake: returning two different types from a -> some Shape function.
SomeTwoTypes.swift
protocol Shape { func area() -> Double}struct Square: Shape { let side: Double func area() -> Double { side * side }}struct Rectangle: Shape { let width: Double let height: Double func area() -> Double { width * height }}func makeShape(wide: Bool) -> some Shape { if wide { return Rectangle(width: 2, height: 1) } return Square(side: 1)}
errores/SomeTwoTypes.swift:16:6: error: function declares an opaque return type 'some Shape', but the return statements in its body do not have matching underlying types [#OpaqueTypeInference]14 | }15 |16 | func makeShape(wide: Bool) -> some Shape { | `- error: function declares an opaque return type 'some Shape', but the return statements in its body do not have matching underlying types [#OpaqueTypeInference]17 | if wide {18 | return Rectangle(width: 2, height: 1) | `- note: return statement has underlying type 'Rectangle'19 | }20 | return Square(side: 1) | `- note: return statement has underlying type 'Square'21 | }22 |[#OpaqueTypeInference]: <https://docs.swift.org/compiler/documentation/diagnostics/opaque-type-inference>
"An opaque type" means one type: every return has to return the same one. If the function
really can return either of the two, the return type is any Shape.
If you come from Java or TypeScript. A protocol with an extension resembles a Java interface
with default methods. With TypeScript there's a deeper difference: TypeScript is structural (an
object conforms to an interface if it has the right shape), and Swift is nominal: a type conforms
to a protocol only if it declares it, even if it has every method.
What to take away: depend on capabilities, not types; some by default, any to mix.
Check what you learned. Can a -> some Shape function return a Square in one return and a
Rectangle in another?
Solution
no. some promises a single concrete type across every return; that's the error in
SomeTwoTypes.swift. To return different types, the return type is any Shape.
Going deeper
the difference isn't one of style. An any Shape value is called an
existential: a value of some type that conforms to the protocol, kept in a box. some
preserves the type's identity: the compiler knows which one it is and can work with it directly.
any can add a box (in the current implementation, small values fit inside without a separate
allocation), a level of indirection (one more step to reach the value) that the Swift
documentation says has a performance cost.
some on a parameter (func draw(_ s: some Shape)) isn't an opaque type but a shorthand for
a generic, which you'll see in the next section. And two facts that often get repeated wrong:
Swift 6 mode does not require you to write any (that's done by a separate feature,
ExistentialAny, which you turn on separately), and since Swift 6.4 you can write some Shape?
instead of (some Shape)?.
Going deeper
why describe() has to be a requirement. A method that exists only in the
extension, and not in the protocol, doesn't behave the same when you call it through an
existential:
With the concrete type, both calls use Robot's versions. Through any Greeter, greet() (a
requirement) uses Robot's, but wave() (only in the extension) uses the extension's: the compiler
picks that method by the type it sees, any Greeter, and not by the one inside the box. If you
want a type to be able to replace a method, declare it in the protocol.
Generics
The largest of a list of numbers and the last title in alphabetical order are the same algorithm.
Why write it twice?
A generic is code written once for many types. You've been using generics from the start without
naming them: [Int] is Array<Int>, and Int? is Optional<Int>.
Generics.swift
func largest<T: Comparable>(_ values: [T]) -> T? { // T: any type that supports < and > guard var best = values.first else { return nil // an empty array has no largest value } for value in values where value > best { best = value } return best}print(largest([3, 9, 4]) ?? 0)print(largest(["pear", "apple", "plum"]) ?? "-")print(largest([Int]()) == nil)struct Stack<Element> { // a generic type private var items: [Element] = [] mutating func push(_ item: Element) { items.append(item) } mutating func pop() -> Element? { return items.popLast() }}var stack = Stack<String>()stack.push("a")stack.push("b")print(stack.pop() ?? "-", stack.pop() ?? "-", stack.pop() ?? "empty")
9plumtrueb a empty
func largest<T: Comparable>(_ values: [T]) -> T? reads like this: for any type T that conforms to
Comparable, take an array of T and return an optional T. Three things:
<T: Comparable> declares the type parameterT with a constraint: T has to conform to the
Comparable protocol, which is the one that provides < and >. Without the constraint,
value > best wouldn't compile: the compiler wouldn't know that two Ts can be compared.
It returns T? because an empty array has no largest value. The third line of the output proves
it.
guard var is like guard let, but the value stays mutable: the loop changes best.
for value in values where value > best walks only the values that meet the condition.
In real code you wouldn't write largest: the library already has max(), with the same constraint
and the same optional. Here it serves to show how it's built.
Stack<Element> is a generic type: a stack that holds elements of any type. You pick it when you
create it (Stack<String>()), and from then on the compiler won't let you push a number.
A protocol can also leave a type undecided, with an associated type:
AssociatedType.swift
protocol Container { associatedtype Item // a type name each conforming type fills in var items: [Item] { get }}struct Shelf: Container { // Item is inferred: String var items: [String]}let shelf = Shelf(items: ["mug", "lamp"])print(shelf.items.count)
2
associatedtype Item reserves a type name that each adopting type fills in: Shelf stores
[String], so its Item is String. That's how Collection is built in the standard library.
The Type Is Still There at Runtime
TypeAtRuntime.swift
func typeName<T>(of value: T) -> String { return String(describing: T.self) // T is still known while the program runs}print(typeName(of: 42))print(typeName(of: "hi"))print(typeName(of: [1.5]))
IntStringArray<Double>
Inside typeName, T.self is the type the function was called with, and the program can name it
while it runs: Int, String, Array<Double>.
If you come from Java. Java erases type parameters at compile time: inside a generic method you
can't ask what T is. The example above shows that in Swift the type is still available at runtime.
What to take away: a generic writes the code once, with the constraints it needs.
Check what you learned. Why does largest require T: Comparable?
Solution
because it compares with >, and only types that conform to Comparable guarantee
that operator. Without the constraint, the body doesn't compile.
Going deeper
library protocols can declare primary associated types, which let you write
some Collection<String> ("some collection whose elements are String") without declaring a
generic. They arrived in Swift 5.7, as did constrained existentials (any Collection<String>).
ARC: Who Keeps an Object Alive
Note: good place for a break: you're about halfway through the guide.
You close a screen and its memory should be released. If it isn't, you have a memory leak: memory
the program no longer uses but doesn't give back either, and that piles up every time you open and
close that screen. In Swift, the cause is almost always the same, and it comes down to a single idea:
counting references.
Structs and enums don't need any of this: they're copied and disappear with the variable that holds
them. Class instances are shared, so someone has to decide when nobody uses them anymore. That
someone is ARC (Automatic Reference Counting): the compiler inserts code that counts how many
strong references point to each class instance. As long as there's at least one, the instance
lives. When the count reaches zero, ARC frees it, and right before that it calls its deinitializer,
deinit.
ArcDeinit.swift
final class Screen { let name: String init(name: String) { self.name = name print("created", name) } deinit { // runs right before ARC frees the instance print("deinit", name) }}var first: Screen? = Screen(name: "Home") // 1 strong referencevar second = first // 2first = nil // 1: still aliveprint("still alive:", second?.name ?? "-")second = nil // 0: ARC frees it and calls deinitprint("done")
created Homestill alive: Homedeinit Homedone
first and second are of type Screen? so they can be set to nil, which is how you let go of a
reference. deinit is the deinitializer: the code that runs right before the instance goes away
(among the types you use every day, only classes have one; noncopyable types, ~Copyable, can
have one too). Follow the count step by step:
The reference counter
Strong references
first (discarded)
second (discarded)
Live object
Freed
Screen "Home" (discarded)
Step 5 of 5
Step 5 of 5: Careful: an object's guaranteed lifetime ends at its last use. You can't tell here, because the last use is second?.name and there's nothing else between it and second = nil.
var first = Screen(name: "Home"). The object is created and first points to it: 1 strong reference.
var second = first. Now there are 2 strong references to the same object.
first = nil. 1 reference is left: the object is still alive, and second?.name still gives "Home".
second = nil. The count reaches 0: ARC calls deinit and frees the object.
Careful: an object's guaranteed lifetime ends at its last use. You can't tell here, because the last use is second?.name and there's nothing else between it and second = nil.
The Retain Cycle
ARC doesn't walk the object graph (the map of which object points to which) looking for objects nobody can reach anymore: it only counts. If
object A has a strong reference to B and B has another one to A, each keeps the other's count at 1,
even if the rest of the program has no way to reach either of them. That's a retain cycle: two
or more objects that keep each other alive and are never freed.
On iOS, the most common cycle isn't between two objects but between an object and a closure. Recall
from "Closures" that a closure is a reference type and keeps alive what it captures. If an object
stores a closure in a property and the closure uses self, the object keeps the closure alive and the
closure keeps the object alive:
ClosureCycle.swift
final class Downloader { let name: String var onFinish: (() -> Void)? // the downloader keeps the closure init(name: String) { self.name = name } deinit { print("deinit", name) } func startLeaking() { onFinish = { print("finished", self.name) } // the closure keeps self: a cycle } func start() { onFinish = { [weak self] in // weak: this arrow doesn't count print("finished", self?.name ?? "-") } }}var leaky: Downloader? = Downloader(name: "leaky")weak var leakyProbe = leaky // a weak probe to see if it was freedleaky?.startLeaking()leaky = nilprint("without fix:", leakyProbe == nil ? "freed" : "still alive")var fixed: Downloader? = Downloader(name: "fixed")weak var fixedProbe = fixedfixed?.start()fixed = nilprint("with [weak self]:", fixedProbe == nil ? "freed" : "still alive")
without fix: still alivedeinit fixedwith [weak self]: freed
leakyProbe and fixedProbe are weak references, explained below: they don't keep anyone alive,
and they become nil when the object is freed. They work as probes: if the probe still has a value
after you let go of the last variable, the object wasn't freed. With startLeaking(), leaky = nil
doesn't free it: the closure still holds on to it and deinit leaky is never printed. With
start(), it does. (fixedProbe == nil ? "freed" : "still alive" is the ternary operator: if the
condition is true it gives the first value, otherwise the second.)
An object stores a closure that captures it strongly: the count never reaches zero. With weak, the arrow back doesn't count.
How to Break It: weak and unowned
You break a cycle by making one of its arrows not count. Swift has two ways:
weak: a reference that doesn't increase the count. When the object is freed, ARC sets it to
nil on its own; that's why a weak property is always optional. In a closure you
write it in the capture list, [weak self], and inside, self is optional (self?.name).
unowned: it doesn't increase the count either, but it isn't optional and ARC doesn't set it
to nil. Use it only when the other object is guaranteed to live at least as long as this one.
Accessing an unowned reference after its object has been freed is a runtime error that stops the
app.
Going deeper
weak let. For years, a weak property had to be a var. Since Swift 6.3
(proposal SE-0481) it can also be a let: it's assigned once, and ARC still sets it to nil when
the object is freed. It's for a class that doesn't change after it's created (in part 2 you'll see
why that matters when sharing it between threads) and needs a weak reference.
WeakLet.swift
final class Owner { let name: String init(name: String) { self.name = name }}final class Badge { weak let owner: Owner? // assigned once, and still becomes nil when Owner is freed init(owner: Owner) { self.owner = owner }}var ana: Owner? = Owner(name: "Ana")let badge = Badge(owner: ana!)print("owner:", badge.owner?.name ?? "-")ana = nilprint("after release:", badge.owner?.name ?? "-")
owner: Anaafter release: -
Inside a closure with [weak self], writing self?. on every line gets awkward. The usual approach
is to unwrap it once at the top, with the guard let from "Optionals":
GuardLetSelf.swift
final class Uploader { let name: String var onDone: (() -> Void)? init(name: String) { self.name = name } deinit { print("deinit", name) } func start() { onDone = { [weak self] in guard let self else { return } // freed already: nothing to do print("done", self.name) // from here on, self is a normal reference } }}var uploader: Uploader? = Uploader(name: "photo")weak var probe = uploaderuploader?.start()uploader?.onDone?()uploader = nilprint(probe == nil ? "freed" : "still alive")
done photodeinit photofreed
guard let self else { return } says: if the object has already been freed, there's nothing to do;
if it's still alive, from here on self is a normal reference until the closure finishes. It doesn't
recreate the cycle: the strong reference lives only while the closure runs.
The other classic UIKit cycle is the delegate one: an object that tells another what's happening.
The screen owns its editor, and the editor notifies the screen when it saves. If both references were
strong, neither would ever be freed. The convention is for the delegate to be weak:
DelegateCycle.swift
protocol EditorDelegate: AnyObject { // AnyObject: only classes can adopt it func editorDidSave()}final class Editor { weak var delegate: EditorDelegate? // weak: the editor doesn't own its delegate func save() { delegate?.editorDidSave() } deinit { print("deinit Editor") }}final class EditScreen: EditorDelegate { let editor = Editor() // the screen owns its editor (strong) init() { editor.delegate = self } func editorDidSave() { print("saved") } deinit { print("deinit EditScreen") }}var screen: EditScreen? = EditScreen()screen?.editor.save()screen = nil // no cycle: both are freed
saveddeinit EditScreendeinit Editor
AnyObject in the protocol restricts adoption to classes: only a reference to a class can be weak.
And a case for unowned: a card that can't exist without its customer.
Unowned.swift
final class Customer { let name: String var card: Card? init(name: String) { self.name = name } deinit { print("deinit Customer", name) }}final class Card { unowned let owner: Customer // a card never outlives its owner init(owner: Customer) { self.owner = owner } deinit { print("deinit Card") }}func demo() { let ana = Customer(name: "Ana") ana.card = Card(owner: ana) print("owner:", ana.card?.owner.name ?? "-")}demo()print("after demo")
The customer owns the card (strong) and the card points to the customer with unowned. When demo()
returns, nobody holds on to the customer: it's freed, and with it goes its reference to the card,
which is freed afterwards.
The usual mistake: using unowned to avoid writing if let or ?. If the object has already
been freed, accessing the reference stops the app. And its relative unowned(unsafe) is worse: it
turns off the check and reads the memory where the object used to be. When in doubt, weak.
An object lives, at minimum, until its last use, not necessarily until the end of the block; the
detail is in the box.
Going deeper
an object doesn't live "until the closing brace". If you come from C++, you
may expect an object to live until the end of the block where it was declared. In Swift that
isn't guaranteed: an object's minimum guaranteed lifetime starts when it's created and ends at
its last use. That it lives a little longer today is a compiler detail that can change with
optimizations.
It matters when the deinit has side effects or when a weak reference depends on the object
still being alive. If you need it to live until a specific point, you say so with
withExtendedLifetime(object) { … }, which guarantees it isn't destroyed before the closure
finishes. The examples in this section use the object between the lines that print, so the order
of the output doesn't depend on that detail.
If you come from Java or JavaScript. Neither the JVM specification nor the JavaScript one pins
down how memory is freed, but the usual implementations (HotSpot in Java, modern JavaScript engines)
use garbage collectors that start from what the program can reach and free the rest, cycles
included. ARC doesn't walk anything: it counts references. That's why in Swift a cycle is a leak, and
in those implementations it isn't.
What to take away: ARC counts strong references; a cycle never reaches zero, and you break it with weak or unowned.
Check what you learned. A TaskListScreen class stores var onFinish: (() -> Void)? and assigns
it a closure that calls self.reload(). Is there a retain cycle?
Solution
yes. The screen holds on to the closure (its property) and the closure holds on to the
screen (it captures self strongly). You break it with [weak self] in the closure, or by letting
go of the closure (onFinish = nil) once it's no longer needed.
Going deeper
three nuances, and one tool. To find cycles in a real app you use Xcode's
Memory Graph Debugger, which draws who retains whom while the app runs; you'll see it in part
3.
When ARC sets a weak reference to nil, its property observers (didSet) don't fire: you
won't find out that way. An object's observed lifetime (when its deinit prints in a test)
isn't the guaranteed one, so a leak test compares against a weak reference after letting go of
everything, like the probes in ClosureCycle.swift.
A non-escaping closure never needs [weak self]: it ends with the call and can't form a cycle.
And in part
2
you'll see that a concurrency task releases its closure when it finishes, which is why it rarely
needs it; while it runs, it does hold on to what it captures, and a task that never finishes is
a cycle by another name.
Errors
Saving a task without a title should fail, and the caller has to find out why. In Swift, the fact
that a function can fail is written in its signature.
A function that throws errors declares throws in its signature; inside it, throw cuts the
function short with an error. An error is any type that adopts the Error protocol, and the normal
thing is an enum with one case per reason:
Errors.swift
enum ValidationError: Error { case empty case tooLong(limit: Int)}func validate(title: String) throws -> String { if title.isEmpty { throw ValidationError.empty } if title.count > 10 { throw ValidationError.tooLong(limit: 10) } return title}for input in ["Milk", "", "A very long title"] { do { let title = try validate(title: input) print("valid:", title) } catch ValidationError.empty { print("error: empty title") } catch ValidationError.tooLong(let limit) { print("error: more than \(limit) characters") } catch { print("error:", error) // any other error }}let maybe = try? validate(title: "") // the error becomes nilprint("try?:", maybe ?? "nil")let result = Result { try validate(title: "Bread") } // the outcome as a valueswitch result {case .success(let title): print("result:", title)case .failure(let error): print("result failed:", error)}
valid: Milkerror: empty titleerror: more than 10 characterstry?: nilresult: Bread
Whoever calls a throwing function has to write try in front of the call: that way, when you read
the code, you see which lines can fail. And they have to do something with the error.
The first thing they can do is not handle it there: propagate it. If the calling function is
also throws, the try is enough, and the error travels on to whoever called it, up to the first
catch that handles it. It's the most common case in an app: the function that validates throws,
the one that saves lets it through, and the screen, which knows what to show, catches it.
Propagation.swift
struct EmptyTitle: Error {}func validate(_ title: String) throws -> String { if title.isEmpty { throw EmptyTitle() // 1. the error starts here } return title}func save(_ title: String) throws { let valid = try validate(title) // 2. no catch: try passes it on print("saved:", valid) // skipped when validate throws}func saveTapped(_ title: String) { do { try save(title) } catch { print("caught in saveTapped:", error) // 3. the first catch that handles it }}saveTapped("Milk")saveTapped("")
saved: Milkcaught in saveTapped: EmptyTitle()
save has no catch: with "", the error leaves validate, skips the print in save, and
reaches the catch in saveTapped. A catch that filters by case, like the ones below, doesn't
stop it either if it doesn't match: the error keeps going up. The other three ways handle it on the spot, and the
Errors.swift example shows them:
do/catch. The try goes inside a do, and the catch clauses catch the error. They can
filter by case (catch ValidationError.empty), pull out associated values
(catch ValidationError.tooLong(let limit)), and end with a catch with no pattern that catches
the rest, with the error in a constant named error.
try? turns the error into nil: the result is an optional. It's useful when you don't care
about the reason, only whether it worked.
Result stores the outcome as a value: .success with the value or .failure with the
error. It's useful for keeping an outcome and processing it later.
That leaves try!, which stops the program if an error is thrown: the same rule as ! on
an optional.
Why this design? Because the error is part of the signature: throws tells you which functions can
fail and try tells you on which lines. Also, throwing an error in Swift doesn't unwind the stack
like an exception in other languages: there's no separate mechanism that walks the call stack
looking for someone to catch it. The error goes back to the caller as a special return value, which
the compiler forces you to handle or to pass on with try.
The usual mistake: a try? that silences an error that needed to be shown. If someone types an
empty title and your code does try? validate(title:), the form isn't saved and nobody knows why.
try? is for when there truly is nothing to say.
defer: Cleaning Up on the Way Out
defer schedules a block for when the code leaves the current scope, however it leaves: by reaching
the end, by a return, or by an error. If there are several, they run in reverse order:
DeferOrder.swift
func work() { defer { print(1) } defer { print(2) } defer { print(3) } print("working")} // on the way out: the last defer runs firstwork()
working321
It's used to close what you opened (a file, a "loading" indicator) right next to where you opened
it, without repeating it at every exit.
Going deeper
typed errors and rethrows. Since Swift 6.0 a function can say which type of error it throws, with throws(Type):
TypedThrows.swift
enum ParseError: Error { case notANumber(String)}func parse(_ text: String) throws(ParseError) -> Int { // only ParseError can come out guard let number = Int(text) else { throw .notANumber(text) } return number}do { print(try parse("12")) print(try parse("x"))} catch { switch error { // error is a ParseError here, not any Error case .notANumber(let text): print("not a number:", text) }}
12not a number: x
In the catch, error is already a ParseError, and the switch can be exhaustive without a
default. An untyped throws is equivalent to throws(any Error). Should you type all your errors?
No: the official guide says most Swift code doesn't specify the error type, and it reserves typed
errors for specific cases you'll see in the box below. The error type becomes part of the function's
public contract: changing it later can break code that depends on that concrete type (code that only
propagates the error as any Error won't notice).
rethrows is for functions that take a closure: the function throws only if the closure throws.
Rethrows.swift
func applyTwice(_ transform: (Int) throws -> Int, to value: Int) rethrows -> Int { return try transform(try transform(value))}print(applyTwice({ $0 * 3 }, to: 3)) // the closure can't throw: no try neededenum LimitError: Error { case tooBig}do { let value = try applyTwice({ number in if number > 10 { throw LimitError.tooBig } return number * 4 }, to: 3) print(value)} catch { print("error:", error)}
27error: tooBig
With a closure that doesn't throw, the call doesn't need try. That's how sorted(by:) works.
map, since Swift 6, achieves the same with typed errors: it throws exactly the error type your
closure throws.
If you come from Java. As with checked exceptions, the error shows up in the signature
(throws). Unlike Java, Swift also marks each call with try (in Java the call carries no marker:
it only has to sit inside a try/catch or in a method that declares the exception); an untyped
throws doesn't list the error types, and throwing doesn't unwind the stack.
What to take away: that a function can fail is in its signature, and every call that can fail carries try.
Check what you learned. If parse(_:) throws with "x", what's the value of try? parse("x")?
Solution
nil. try? turns any error into an empty optional; if it doesn't throw, the value
comes wrapped in an optional.
Going deeper
the Swift guide reserves typed errors for three cases: embedded code (code
that runs on small devices) or code without dynamic memory allocation (no requesting new memory
while it runs), a library's internal errors that never leave it, and generic functions that only
propagate their closure's error.
throws(Never) is equivalent to not throwing, which lets you write generic functions that throw
or not depending on their parameter. And since Swift 6.4 a defer can await asynchronous work
(work that finishes later, without blocking the thread), which completes before leaving the
scope; you'll see asynchronous code in part
2.
Anatomy of an iOS App
Note: good place for another break: you're about two thirds of the way, around 1 h 30. What
follows changes ground: from the language to the app.
What happens between tapping an app's icon and seeing its first screen? To see it you need Xcode,
and the first thing is to get the Mac ready.
Before the Project: the Mac, Xcode, and the Simulator
What does your Mac need before the first project? Four things, all free:
macOS Tahoe 26.6 or later, the minimum Xcode 27.2 asks for. Your version is in Apple
menu › About This Mac, or in the terminal with sw_vers.
Xcode, from the Mac App Store. Betas (test versions released before the final one) and
older versions are on the Xcode resources
page, with your Apple Account and without paying
for any membership.
The first launch. Open Xcode once and let it install its components, or do it in the
terminal with sudo xcodebuild -runFirstLaunch (sudo asks for your administrator password).
I didn't run this command on my Mac: I cite it from Apple's documentation.
The iOS simulator, which downloads separately: Xcode › Settings…, Components section,
or in the terminal with xcodebuild -downloadPlatform iOS. It takes several GB: on my Mac,
-downloadPlatform iOS downloaded two iOS 27.2 images of about 8.3 GB each (that's why
simctl lists two), and xcrun simctl runtime list adds them up to 15.5 GB.
Three commands check the setup: xcode-select -p says which Xcode the terminal uses,
xcodebuild -version its version, and xcrun simctl list runtimes the simulator systems
installed. On my Mac:
One iOS 27.2 line is enough. If xcode-select -p points to another folder, choose the Xcode you
installed with sudo xcode-select -s /Applications/Xcode.app.
What about the Apple account? The simulator needs none: this Mac has no account signed in to
Xcode, and everything in this part ran that way. With a free Apple Account you can also install
your apps on your own iPhone. Xcode shows it as a Personal Team, and what you install that way
expires after 7 days, with at most 3 apps per device.
TestFlight (Apple's service for handing out test versions) and the App Store require the Apple
Developer Program, which is paid. You enroll as an individual, and sell under your legal name, or
as an organization: a legal entity with a D-U-N-S Number, the nine-digit business identifier that
Dun & Bradstreet assigns, free in most countries.
I didn't run the iPhone and publishing steps, because this Mac has no account: I describe them from
Apple's documentation. The step-by-step guide is in part 4, in "From the Simulator to Your
iPhone and the App Store".
Your First Project
This part's examples live in a lab project called SampleApp
(download it, with its tests). You'll create your own and add
the same files to it, section by section; if you get lost, compare with the one in the zip. This is
how you create it in Xcode 27.2:
File › New › Project…, iOS tab, App template, and Next.
Product Name:SampleApp. Interface: SwiftUI. Language: Swift. Testing System:
Swift Testing. Storage: None. Next, pick a folder, and Create.
In the navigator on the left, click the project (the blue icon at the top) and, in the
Targets list, SampleApp. A target is a product the project builds: the app, and separately
its tests.
Build Settings tab, search for "Swift Language Version" and choose Swift 6: the Xcode 27.2
template ships Swift 5 mode.
General tab, Minimum Deployments section: iOS 18.0, the oldest iOS version the app
can be installed on (Xcode 27.x supports iOS 15 through iOS 27).
In the toolbar, pick the iPhone 17 simulator (a pretend iPhone that runs on the Mac) as the
destination and press ⌘R (or the ▶ button).
Try it yourself: Xcode builds, opens the simulator, and launches the app. You see the
template's screen: a globe and the text "Hello, world!". To stop it, ⌘. (or the ■ button).
Your first app in the iPhone 17 simulator, with iOS 27.2.
After steps 4 and 5, the target has these settings (I read them from the lab's project file):
The template sets the last two, and they change how code compiles. The first is default
isolation: it decides which actor (a region of the program that protects its data from
simultaneous access) each declaration in your module belongs to unless you say otherwise. With
this setting, your types belong to the main actor, the one for the main thread, where iOS draws
the interface and receives taps.
It doesn't make everything run there: system code that calls you back can arrive from another
thread, as you'll see in "Permissions and Privacy". The second turns on a group of rules that make
concurrency easier to write. A standalone file compiled with swiftc, like the ones in the
earlier sections, or a Swift package, doesn't have them turned on. Part
2
explains both.
The Pieces
This is the app's entry point. Xcode created it as SampleAppApp.swift, without the
@UIApplicationDelegateAdaptor line, which you add further down:
SampleApp/SampleAppApp.swift
import SwiftUI@main // the entry point: the system starts herestruct SampleAppApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate var body: some Scene { WindowGroup { // one scene; each window gets its own state ContentView() // the root view of every window } }}
Piece by piece:
@main marks the type where the program starts. An app has exactly one.
App is the protocol that type adopts. All it requires is body, which describes the app's
scenes.
A scene (Scene) is a part of the interface that the system manages with its own life cycle:
on an iPhone, your app's window; on an iPad, there can be several at once. some Scene is the
opaque type from "Protocols and Extensions": some concrete kind of scene.
WindowGroup is the most common scene: it creates the app's windows, and each window keeps
its own state, independent of the others.
ContentView() is the root view: the first thing drawn in each window. In the lab it picks
between several test screens; in your project, in "The Scene Life Cycle", it will show
WelcomeView.
Why scenes? Since the iOS 27 SDK, an app must use the scene-based life cycle: if it doesn't, it won't launch. A SwiftUI
app with App and WindowGroup already complies. The same SDK requires a launch screen, which the
template generates from a project setting.
Beneath SwiftUI: UIKit
SwiftUI is built on UIKit, Apple's earlier interface framework. Beneath your App there's a
UIApplication object (the running app), one UIWindowScene per scene, and a
UIWindow that shows your views.
The pieces of a SwiftUI app and what lies beneath; on the right, the phases of a scene.
You almost never touch those pieces. For the little that SwiftUI doesn't cover (for example, a
third-party SDK that asks for an app delegate, an object UIKit notifies about the app's events),
there's @UIApplicationDelegateAdaptor. Create it like this:
File › New › File from Template… (⌘N), iOS › Swift File, name it AppDelegate, and
Create. Give it this content:
SampleApp/AppDelegate.swift
import UIKitfinal class AppDelegate: NSObject, UIApplicationDelegate { private(set) static var launchCount = 0 func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { AppDelegate.launchCount += 1 // UIKit calls this when the process has launched return true }}
In SampleAppApp.swift, add the @UIApplicationDelegateAdaptor line inside the struct, as in
the block above.
AppDelegate is a class that adopts UIApplicationDelegate and inherits from NSObject, the base
class of UIKit's objects (it comes from Objective-C, Apple's earlier language). UIKit calls
application(_:didFinishLaunchingWithOptions:) once the process has finished launching. Its
parameter is an optional dictionary whose values are Any, which means "of any type".
Try it yourself: click the line number of AppDelegate.launchCount += 1 to set a
breakpoint (a blue marker where Xcode pauses the app) and press ⌘R. Xcode stops there once, at
launch. Click the marker again to remove it and press ⌃⌘Y to continue.
Two rules from Apple's documentation: declare the adaptor only once, in your App (two declarations
are a runtime error), and avoid it when you can: for the life cycle, SwiftUI has its own tool, which
you'll see in the next section.
What to take away: a SwiftUI app is an @main type that describes scenes; UIKit is still
underneath, and you rarely touch it.
Check what you learned. What happens if you declare @UIApplicationDelegateAdaptor in two
places in the app?
Solution
SwiftUI raises a runtime error. The adaptor is declared once, in the App type.
The Scene Life Cycle
People don't use your app in one go: they open it, look at the list of open apps, switch to another
app, come back. The system tells each scene about those changes through its scene phase
(ScenePhase), which has three values:
Phase
What it means
What to do
.active
in the foreground and receiving events
resume what you paused
.inactive
not receiving events; it may be visible or hidden
pause timers and free what isn't needed
.background
off screen
save what's pending: this phase can precede termination
A scene in .background may come back to the foreground, but the system may also terminate it
without further notice: it's the time to save what's pending, and "Saving" shows how.
Create two files:
File › New › File from Template… (⌘N), iOS › Swift File, named SceneAction, with this
content:
SampleApp/SceneAction.swift
import SwiftUIenum SceneAction: Equatable { case resume // back in the foreground: start timers, refresh case pause // not receiving events, maybe hidden: pause timers case save // in the background: the app may be terminated, save now init(for phase: ScenePhase) { switch phase { case .active: self = .resume case .inactive: self = .pause case .background: self = .save @unknown default: // a phase added by a future iOS self = .pause } }}
File › New › File from Template…, iOS › SwiftUI View, named WelcomeView. Replace what
it contains with this (you can keep the #Preview block at the end, which draws the view in
Xcode's canvas):
SampleApp/WelcomeView.swift
import SwiftUIstruct WelcomeView: View { @Environment(\.scenePhase) private var scenePhase // the phase of this view's scene var body: some View { Text("Welcome") .font(.largeTitle) .onChange(of: scenePhase) { oldPhase, newPhase in let action = SceneAction(for: newPhase) print("scene:", oldPhase, "->", newPhase, "action:", action) } }}
In ContentView.swift, replace what's inside body (the VStack with the globe) with
WelcomeView().
SceneAction turns each phase into what the app should do, and it can be tested without any
interface. The switch over ScenePhase needs something new: @unknown default. ScenePhase is
an enum from an Apple framework that may gain cases in a future iOS version, and Swift 6 mode
requires you to say what to do with a case that doesn't exist today. Unlike a default,
@unknown default warns you if the new case shows up and you didn't handle it.
In WelcomeView, @Environment(\.scenePhase) has two new pieces. Here, the @ marks a property
wrapper: a type that decides how the property is stored and read, and SwiftUI ships several. Not
every @ is one: in part 2 you'll see macros (code the compiler generates for you), which are
also written with @. \.scenePhase is a key path, the name of a property written as a value:
here, which of the data the system passes to the view you want to read.
That mechanism, SwiftUI's environment, is part
2.
Read in a view, the phase is that of its scene; read in the App type, it summarizes all of
them. .font(.largeTitle) and .onChange(of:) are modifiers: each returns the view with one
change, here large text and a reaction. .onChange(of:) runs its closure every time the value
changes, with the old value and the new one.
Try it yourself: press ⌘R; now you see "Welcome". Open the console with ⇧⌘Y (the area at the
bottom of Xcode). In the simulator, Device › Home (⇧⌘H) takes you to the home screen, and
tapping the SampleApp icon brings you back. The console shows one line at launch (the scene goes
from .inactive to .active) and four more for the trip to the home screen and back:
scene: inactive -> active action: resumescene: active -> inactive action: pausescene: inactive -> background action: savescene: background -> inactive action: pausescene: inactive -> active action: resume
It's the same sequence a UI test in the lab
(SampleAppUITests.swift) checks by pressing Home and reopening the app.
Saving: On Every Change, and What's Pending on the Way Out
Waiting for .background to save everything is a mistake: if the app crashes first, what the
person did is lost. Production apps save when each change is confirmed (when the person finishes
editing a field, for example) and, on entering .background, save whatever is still pending.
.background is the last guaranteed chance, not the only one. Interview exercise 2 implements it. If
saving takes more than an instant, UIKit has beginBackgroundTask(withName:expirationHandler:),
which asks the system for extra time in the background and requires you to say when you're done.
The system decides the order of the phases. This sequence follows the ScenePhase documentation
and what the console showed:
From opening the app to closing it
User
System
Scene
Your view
User → Systemtaps the iconUser calls System: taps the icon
System → Scenecreates the sceneSystem creates Scene: creates the scene
Scene → Your viewscenePhase = .activeScene calls Your view: scenePhase = .active
User → Systemopens the app switcherUser calls System: opens the app switcher
Scene → Your viewscenePhase = .inactiveScene calls Your view: scenePhase = .inactive
User → Systemreturns to the appUser calls System: returns to the app
Scene → Your viewscenePhase = .activeScene calls Your view: scenePhase = .active
User → Systemswitches to another appUser calls System: switches to another app
Scene → Your viewscenePhase = .inactiveScene calls Your view: scenePhase = .inactive
Scene → Your viewscenePhase = .backgroundScene calls Your view: scenePhase = .background
User → Systemreturns to the appUser calls System: returns to the app
Scene → Your viewscenePhase = .inactiveScene calls Your view: scenePhase = .inactive
Scene → Your viewscenePhase = .activeScene calls Your view: scenePhase = .active
Step 13 of 13
Step 13 of 13: Active again and receiving events.
The person opens the app from the home screen.
The system creates the WindowGroup scene and its root view.
The app is in the foreground and receives taps: your view resumes whatever it needs.
The person swipes to see the open apps.
The scene doesn't receive events: it may only be visible as a thumbnail in the switcher. Pause timers.
They pick your app again.
Back in the foreground and receiving events.
The person opens another app.
Before leaving the screen, the scene stops receiving events.
Off the screen. Flush whatever is pending: the system can terminate the app with no further warning.
If the system didn't terminate it, the person can come back, with the state still in memory.
On its way to the foreground, the scene goes through inactive.
Active again and receiving events.
What to take away: save on every confirmed change, and what's pending on entering
.background.
Check what you learned. When do you save what the person typed, so it isn't lost if the system
terminates the app?
Solution
when each change is confirmed, and also when the scene enters .background, to save
whatever is still pending. .background is the last guaranteed chance, not the only one: waiting
only for it loses data if the app crashes first.
Going deeper
beneath ScenePhase is UIKit's UIScene.ActivationState, with four states
(unattached, foreground inactive, foreground active, and background). A scene can be disconnected
while the process stays alive, and be created again later; to bring back what was on screen,
SwiftUI has @SceneStorage, which is outside this series. In iOS 27, the extendStateRestoration()
and completeStateRestoration() methods of UIScene, available since iOS 15, also work for
extending state restoration in the transition from the background to the foreground.
Resources: Images, Info.plist, and Localizable Text
An installed app isn't just code: it carries its icon, its images, its configuration, and its text
in each language. All of that lives in the bundle, the app's folder with the executable and its
resources. In code, Bundle.main represents your app's bundle, and it's how you ask for its files.
Create these two files:
File › New › File from Template…, Other › Empty File, named sample.json, with the text
{"id": 1, "title": "Buy milk", "completed": false}.
File › New › File from Template…, iOS › Swift File, named Resources, with this function
(you'll add another one below):
SampleApp/Resources.swift
func sampleDataSize(in bundle: Bundle = .main) -> Int? { guard let url = bundle.url(forResource: "sample", withExtension: "json") else { return nil // not in the bundle: a build problem } let data = try? Data(contentsOf: url) // reading can fail: try? turns that into nil return data?.count}
url(forResource:withExtension:) returns an optional: the file may not be in the bundle.
Data(contentsOf:) reads the bytes and can throw an error, which try? turns into nil. Reading
the JSON as structured data is part 2.
For a file to end up in the bundle, it has to belong to the app's target. In a new Xcode 27.2
project, the navigator's folders are synchronized with the disk: a file created in the SampleApp
folder belongs to the target with nothing else to do. You check it by selecting the file and looking
at Target Membership in the File inspector (View › Inspectors › File, ⌥⌘1).
Try it yourself: in WelcomeView, add .onAppear { print("sample.json:", sampleDataSize() ?? 0, "bytes") } after .font(.largeTitle) (.onAppear runs its closure when the view appears) and
press ⌘R: the console shows the file's size. Uncheck
sample.json in Target Membership and run again: now it says 0, because the file is no
longer in the bundle. Check it again.
If you ever force that optional with !, it would be the acceptable case from "Optionals": a
resource the compilation copies into the app, whose absence is a build mistake worth seeing right
away.
Besides the code and your files, the bundle has three pieces of configuration:
The asset catalog (Assets.xcassets): the app icon, the accent color, and images, in the
resolutions each device needs. An image from the catalog is shown with Image("name").
Info.plist: the configuration the system reads before running your code, such as the app's
name or its launch screen. In a new Xcode 27.2 project there's no file to edit: Xcode generates it
at build time from the target's settings. You see and edit them in the target, Info tab, or in
Build Settings, searching for "Info.plist Values"; in the project file they're the settings
that start with INFOPLIST_KEY_.
Localizable text, in a String Catalog.
Localizable Text
A String Catalog (an .xcstrings file, since Xcode 15) stores all of the app's translatable
text, with its translation in each language. Create it with File › New › File from Template…,
Resource › String Catalog, named Localizable. When you build, Xcode adds the text from your
code on its own, like Welcome; with the + button at the bottom left of the catalog you add
Spanish (es) and type the translation. This is the lab's:
The key is Welcome, the English text. At build time, Xcode turns it into the bundle's language
folders (en.lproj, es.lproj). Text("Welcome") in a view is already a catalog lookup: SwiftUI
treats the literal text as a key. Outside a view, you ask for it with String(localized:); add it
to Resources.swift:
SampleApp/Resources.swift
func welcomeTitle(in bundle: Bundle = .main) -> String { return String(localized: "Welcome", bundle: bundle) // the key in Localizable.xcstrings}
Try it yourself:Product › Scheme › Edit Scheme… (⌘<), Run › Options, App
Language: Spanish, and ⌘R. The screen says "Te damos la bienvenida". Switch back to System
Language when you're done.
The usual mistake: passing a String variable to Text and expecting it to be translated.
Only literal text is treated as a key; a variable is shown as is, as the Text documentation says.
The lab has a screen with both forms: in Product › Scheme › Edit Scheme… › Run › Arguments,
add -labScreen under Arguments Passed On Launch and, in another row, localization; with the
app in Spanish it shows "Te damos la bienvenida" (the literal) and "Welcome" (the variable with the same text). If the text comes in a
variable, translate it first with String(localized:).
What to take away: what isn't code goes in the bundle, and text is translated by key in the
String Catalog.
Check what you learned. Where does a piece of interface text that gets translated go?
Solution
in the String Catalog, with one entry per language. The code uses the key, with a
literal in Text("…") inside a view or with String(localized:) outside one.
Permissions and Privacy
An app that asks for the camera as soon as it opens, without saying why, usually gets a "no". One
that asks when you tap "scan" and says why gets a "yes". iOS requires you to say why; when to ask is
up to you.
The Usage Description
To use the camera, the microphone, photos, or location, the app has to declare a usage
description in its Info.plist: the text the system shows the person when it asks for
permission, explaining why. If the app tries to use the camera without that key, the system
terminates it. In Xcode you add it in the target, Info tab: in the Custom iOS Target
Properties list, a row's + button and the key "Privacy - Camera Usage Description". In the
lab it ended up like this:
INFOPLIST_KEY_NSCameraUsageDescription = "The camera scans the barcode on a product to add it to your list."
Write it for the person: "to scan a product's barcode" says more than "the app needs the camera".
Try it yourself: in the target, Info tab, the "Privacy - Camera Usage Description" row
shows your text, and ⌘B builds with no errors. With the lab's zip, ⌘U (Product › Test) runs the
tests: one reads the key from the generated Info.plist.
Asking for Permission: In Context, Once, and with the System's Answer
Notifications are requested with UNUserNotificationCenter, and the system shows the dialog only
once: later calls don't ask again, they return the answer the person already gave. That's why
when you ask matters: in context, when the person does something that needs it (for example,
turning on a reminder for a task), not the first time the app opens.
Permission code has to solve five things a naive example forgets: the system keeps the answer, not
your app; two quick taps mustn't ask twice; an error isn't thrown away; someone who said no needs
a way to Settings; and coming back from Settings means reading the answer again. The code below
uses completion handlers (closures the system runs when it answers), the older form of these
APIs (the interfaces the system offers your code): in part
2 you see
the async form of this kind of API, which is shorter.
And it lacks one thing on purpose: telling the view when the state changes, which needs SwiftUI's
observable state from part
2.
Create it as NotificationPermission.swift (iOS › Swift File):
SampleApp/NotificationPermission.swift
import Foundationimport UIKitimport UserNotificationsenum PermissionState: Equatable { case notDetermined // never asked: the system will show its dialog case requesting // the dialog is on screen: don't ask again case granted case denied // only the Settings app can change it now init(_ status: UNAuthorizationStatus) { switch status { case .notDetermined: self = .notDetermined case .authorized, .provisional, .ephemeral: self = .granted case .denied: self = .denied @unknown default: self = .denied } }}/// What the permission logic needs from the system, and nothing else.protocol NotificationAuthorizing { func currentStatus(completion: @escaping @Sendable (UNAuthorizationStatus) -> Void) func requestAuthorization(completion: @escaping @Sendable (Result<Bool, Error>) -> Void)}final class NotificationPermission { private(set) var state = PermissionState.notDetermined private(set) var lastError: Error? private let center: NotificationAuthorizing init(center: NotificationAuthorizing) { self.center = center } /// Reads the real answer from the system: call it every time the screen appears. func refresh() { center.currentStatus { status in DispatchQueue.main.async { guard self.state != .requesting else { return } // a request in flight decides self.state = PermissionState(status) } } } /// Coming back to the app (for example, from Settings) doesn't make the screen appear again: /// read the status again every time the scene becomes active. func handle(_ action: SceneAction) { if action == .resume { refresh() } } /// Asks, in context, only if nobody asked yet and no dialog is on screen. func request() { guard state == .notDetermined else { return } state = .requesting center.requestAuthorization { result in DispatchQueue.main.async { self.finish(result) } } } private func finish(_ result: Result<Bool, Error>) { switch result { case .success(let granted): lastError = nil // an old failure no longer applies state = granted ? .granted : .denied case .failure(let error): lastError = error // keep it: the screen decides how to show it state = .notDetermined } } /// Where a "Turn on notifications" button sends a person who said no. static let settingsURL = URL(string: UIApplication.openNotificationSettingsURLString)}
PermissionState has four states, and its init(_:) maps the state the system keeps
(UNAuthorizationStatus) to the app's.
NotificationAuthorizing is a protocol with the only things the code needs from the system:
reading the current status and requesting authorization. The request reports back with a
Result: the answer's Bool, or the error.
refresh() reads the system's answer; if it arrives while a request is in flight, it doesn't
overwrite .requesting.
handle(_:) calls refresh() every time the scene becomes .active again. Coming back from
Settings, the screen doesn't "appear" again (it never disappeared), but the scene does become
.active: that's the moment to read the new answer. In part 2
you hook it up to .onChange(of:), with SceneAction(for:).
request() asks only from .notDetermined, and moves to .requesting before asking: a second
tap while the dialog is open does nothing.
An error is kept in lastError so the screen can decide how to show it, and a good answer
clears it: that way a retry that works doesn't leave an old error on screen.
settingsURL opens your app's notification settings in the Settings app: where the "Turn on
notifications" button goes when the state is .denied.
@Sendable marks a closure that may run on another thread: the SDK declares its handlers that way
because it doesn't guarantee which thread they arrive on. That's why each answer goes through
DispatchQueue.main.async, which puts that work on the main thread's queue before touching the
state. Why it compiles is in the box.
Going deeper
why this file compiles. With the template's default isolation,
NotificationPermission belongs to the main actor, and a type that belongs to an actor can be
shared between threads safely: that's why the @Sendable closure may capture self. Compiled
without that setting, the class belongs to no actor and the compiler rejects it:
SampleApp/NotificationPermission.swift:41:23: error: capture of 'self' with non-Sendable type 'NotificationPermission' in a '@Sendable' closure [#SendableClosureCaptures] 26 | } 27 | 28 | final class NotificationPermission { | `- note: class 'NotificationPermission' does not conform to the 'Sendable' protocol 29 | private(set) var state = PermissionState.notDetermined 30 | private(set) var lastError: Error? : 39 | center.currentStatus { status in 40 | DispatchQueue.main.async { 41 | guard self.state != .requesting else { return } // a request in flight decides | `- error: capture of 'self' with non-Sendable type 'NotificationPermission' in a '@Sendable' closure [#SendableClosureCaptures] 42 | self.state = PermissionState(status) 43 | }SampleApp/NotificationPermission.swift:61:17: error: capture of 'self' with non-Sendable type 'NotificationPermission' in a '@Sendable' closure [#SendableClosureCaptures] 26 | } 27 | 28 | final class NotificationPermission { | `- note: class 'NotificationPermission' does not conform to the 'Sendable' protocol 29 | private(set) var state = PermissionState.notDetermined 30 | private(set) var lastError: Error? : 59 | center.requestAuthorization { result in 60 | DispatchQueue.main.async { 61 | self.finish(result) | `- error: capture of 'self' with non-Sendable type 'NotificationPermission' in a '@Sendable' closure [#SendableClosureCaptures] 62 | } 63 | }[#SendableClosureCaptures]: <https://docs.swift.org/compiler/documentation/diagnostics/sendable-closure-captures>
This is the protocol's real implementation, the one that calls the system:
Try it yourself: press ⌘B: it builds with no errors or warnings. With the lab's zip, ⌘U
(Product › Test) runs SampleAppTests.swift: its permission tests check, with a fake center,
the four states, the double request, the error, the retry that clears it, and the return from
Settings. The test navigator
(⌘6) marks each one green.
The lab tests it with a fake center that
answers whatever the test asks it to (SampleAppTests.swift); writing tests like that is part 3.
The Privacy Manifest
A privacy manifest is a PrivacyInfo.xcprivacy file (File › New › File from Template…,
Resource › App Privacy) where the app declares the data it collects and the system APIs with a
"required reason" that it uses. That second part is mandatory for publishing. The lab collects no
data and uses none of those APIs, so it has nothing to declare; the detail is in the box below.
What to take away: iOS requires the usage description; you choose the moment, and the answer
is always read from the system.
Check what you learned. What happens if you call requestAuthorization twice?
Solution
the second call doesn't show the dialog again: it returns the answer the person
already gave. That's why it pays to ask in context, and to read the system's status before
showing a button to ask.
Going deeper
what Apple requires of the manifest. According to its documentation, it
records two things: the types of data the app collects from the person (and whether it uses them
to track them across other companies' apps, the NSPrivacyTracking key), and the
required-reason APIs, system APIs that could be used to identify a device, each with the allowed
reason that justifies it. Since May 1, 2024, App Store Connect (the site where apps are
submitted to the App Store) doesn't accept apps that use those APIs without declaring their
reason.
Third-party SDKs bring their own manifest, and those on Apple's list of "SDKs that require a
privacy manifest and signature" must also come signed. The app's preferences store
(UserDefaults, which you'll see in part
3) is
one of those APIs: its category is NSPrivacyAccessedAPICategoryUserDefaults, and the typical
reason is CA92.1, reading and writing data only the app itself can see.
Navigation: The Patterns Before the API
Before you write a new screen, it's worth deciding how people get to it. iOS has four ways, and each
one tells the person something different. You write the code in part 2; here what matters is knowing
which one to pick.
Pattern
What for
Example
Part 2 API
Stack
drilling down: from a list to its detail, and back
a mail app: the inbox and a message
NavigationStack
Modal (sheet)
a separate task, which you finish or cancel
composing a new message
the .sheet modifier
Tabs
sections at the same level, always at hand
a music app: home, search, library
TabView
Deep link
entering a specific screen from outside the app
a link in an email that opens a task
the .onOpenURL modifier
A deep link is a URL (an address, like the ones on the web) that opens the app directly on a
specific screen, instead of the start screen. It forces you to think of navigation as data: if a URL
can say "task 42", the app has to be able to build the stack that leads to it. Apple recommends
universal links (ordinary web addresses that open the app if it's installed) over custom schemes
like myapp://.
Two things you'll find in old code and tutorials:
NavigationView, the navigation stack from the first versions of SwiftUI. Apple recommends
NavigationStack, which arrived in iOS 16. The iOS 27.2 SDK marks NavigationView as
"deprecated in a future version", with no date: that's why Xcode doesn't warn when you use it, and
the web documentation shows the next version, 27.3, as the date.
canOpenURL(_:), which asked whether a URL could be opened before opening it, has been deprecated
since iOS 27.0. The recommendation now is to try opening it and handle the failure; with universal
links, the question isn't even needed.
What to take away: pick the pattern for what it tells the person: drill down, a separate task, sections, or entering from outside.
Check what you learned. A form to create a task, which closes when you save or cancel: stack or
modal?
Solution
modal. It's a separate task with a clear end (save or cancel); a stack is for drilling
into something and coming back the same way.
Interview Questions
Note: good place for a break before the interview: you're more than four fifths of the way,
and what's left is practice, which pays off more with a fresh head.
These are questions asked in iOS interviews about what you've covered in this part. The series has
32, numbered continuously across the four parts; these are the first eleven. Try to answer before
opening the solution, and out loud: in an interview they grade the explanation, not just the answer.
Question 1. (Junior) What does let fix in a struct, and what does it fix in a class?
Solution
in a struct, the whole value: no property can change. In a class, only the reference:
the constant can't point to another object, but the object's var properties can still be
modified. See "Structs and Classes".
Question 2. (Junior) Why does 3 + 0.5 compile while let n = 3 followed by n + 0.5 doesn't?
And what happens with Int.max + 1?
Solution
a literal has no type of its own, and the 3 is inferred as a Double; n is
already an Int, and Swift never converts a number to another type on its own. Int.max + 1 stops
the program at runtime; if the compiler can work it out earlier, it rejects it at compile time,
although it can't always. &+ wraps around on purpose. See "Types and Operators".
Question 3. (Junior) Does copying an Array copy its elements? Can I rely on the order of a
Set?
Solution
it behaves like an independent copy (value semantics), even though the library delays
the real copy until the first modification. A Set has no defined order, and a Dictionary's is
stable only as long as you don't modify it: for a stable order, sorted(). See "Collections".
Question 4. (Junior) What is an optional, and when is ! acceptable?
Solution
a type that represents "a value or none"; it's an enum with the cases .none and
.some. You unwrap it with if let, guard let, ??, or optional chaining. ! is acceptable
only when a nil would be a programming error you'd rather catch with a crash, such as a resource
the compilation puts in the bundle. See "Optionals".
Question 5. (Junior/Mid) How would you model the states of a screen that loads data?
Solution
with an enum with associated values (loading, loaded([Item]), failed(Error))
and an exhaustive switch with no default: the type doesn't admit impossible combinations and the
compiler warns you when you add a state. See "Enumerations".
Question 6. (Mid) A struct holds an instance of a class. You copy the struct and modify the
instance through the copy. What does the original see?
Solution
the change. The copy duplicated the reference, not the object: both structs point to
the same instance. A struct has value semantics only if everything it holds has them too. It's the
verified output of StructWithReference.swift, in "Structs and Classes".
Question 7. (Senior) Is copy-on-write a language guarantee?
Solution
it isn't a language guarantee. What's guaranteed is value semantics: everything
behaves as if the copy happened immediately. Copy-on-write is documented behavior of the library's
collections that you can rely on for cost, and Array documents that sometimes it copies even
less. A struct of your own doesn't have it unless you write it, with
isKnownUniquelyReferenced. See "Collections" and "Structs and Classes".
Question 8. (Mid/Senior) some Shape or any Shape?
Solution
some is a single concrete type the compiler knows and the caller doesn't see: the
type's identity is preserved and there's no box. any is a box that can hold any type conforming to
the protocol, with an indirection cost; you need it to mix types in a collection. Swift 6 mode
doesn't require you to write any. A common follow-up: a method defined only in the protocol's
extension, called through any P, runs the extension's version, not the type's; for the type to be
able to replace it, it has to be a requirement. See "Protocols and Extensions".
Question 9. (Mid) weak or unowned to break a cycle?
Solution
weak is optional and becomes nil when the object is freed: it works whenever the
other object might go away first. unowned isn't optional, and accessing it after the object is
freed stops the app: use it only when the other object is guaranteed to live at least as long as
this one. And a non-escaping closure needs neither: it ends with the call and can't form a cycle.
See "ARC".
Question 10. (Senior) Does an object live until the end of the scope where it was declared?
Solution
that isn't guaranteed. The minimum guaranteed lifetime ends at the last use; living
longer is a compiler detail. To extend it to a specific point, withExtendedLifetime. See "ARC".
Question 11. (Junior/Mid) What happens to an app when it goes to the background, and where do you
save the person's work?
Solution
its scene goes through .inactive to .background, a phase that can come right
before termination. The right approach is to save when each change is confirmed and, on entering
.background, flush whatever is pending: it's the last guaranteed chance, not the only one. Since
the iOS 27 SDK the scene-based life cycle is mandatory, and a SwiftUI app already uses it. See "The
Scene Life Cycle".
Interview Exercises
Seven coding exercises at the level of a technical interview, from junior to senior. The series has twenty, numbered continuously. Each one comes with a statement,
requirements, and constraints; write your solution before opening the proposed one, which includes
the output it gave when it ran, the common mistakes, how it's graded, and a follow-up question.
Exercise 1. The Three Most Frequent Words (Junior). Given an array of lowercase words, print the
three that repeat the most, with their count.
Requirements: on a tie in the count, sort alphabetically; if there are fewer than three distinct
words, print the ones there are.
Constraints: only what you've seen in this part (dictionaries with default:, sorting a
dictionary into pairs with sorted, named tuples, and loops with where); no !.
SolutionEj01TopWords.swift
func topWords(_ words: [String], count: Int) -> [(word: String, count: Int)] { var counts: [String: Int] = [:] for word in words { counts[word, default: 0] += 1 } let ranked = counts.sorted { a, b in // each element is a (key, value) pair if a.value != b.value { return a.value > b.value // more frequent first } return a.key < b.key // ties: alphabetical } var top: [(word: String, count: Int)] = [] for pair in ranked where top.count < count { top.append((word: pair.key, count: pair.value)) } return top}let words = ["the", "cat", "eats", "the", "cat", "sleeps", "the", "dog", "eats"]for entry in topWords(words, count: 3) { print("\(entry.word): \(entry.count)")}
You count with a dictionary and default: 0, as in "Collections". Sorting a dictionary with
sorted gives an array of pairs, each with its key and its value; the closure decides the
order: first the count, from highest to lowest, and on a tie the word. Then a for with where
copies pairs while there are fewer than count, so with fewer than three distinct words it returns
the ones there are. The function returns an array of named tuples (word, count).
Expected result:
the: 3cat: 2eats: 2
Common mistakes: printing the dictionary as is (its order isn't predictable); sorting only by
count, so cat and eats come out in any order; accessing ranked[2] without checking that it
exists, which stops the program with fewer than three words. - Evaluation criteria: a total, stable
order (count, then word); clear names; no !. - Follow-up: what if the words come in a
one-gigabyte text? (Don't load it all: read it in chunks and keep updating the counts.
With map, filter, and prefix from "Closures" the function can also be written in three
lines: which one reads better?)
Exercise 2. The Draft That Doesn't Get Lost (Junior/Mid). Write a DraftSaver that saves a
draft's text with the strategy from "The Scene Life Cycle": when each change is confirmed and, when
the .save action arrives (the one for .background), whatever is still pending.
Requirements: it receives a store through its initializer (a DraftStoring protocol with
save(_:)); it reacts to SceneAction's actions; it never writes to the store a text it already
saved.
Constraints: no real disk writes (the real store is part 3): use a fake store that prints what it
receives. Solve it in the terminal, with its own three-case SceneAction; in the lab,
SceneAction already exists.
SolutionEj02DraftSaver.swift
enum SceneAction { // the same cases as SceneAction in the lab case resume, pause, save}protocol DraftStoring { func save(_ text: String)}final class DraftSaver { private let store: DraftStoring private var pending: String? // typed, not saved yet private var lastSaved: String? // what the store already has init(store: DraftStoring) { self.store = store } func textChanged(_ text: String) { pending = text } func commit() { // the person confirmed the change savePending() } func handle(_ action: SceneAction) { // .save comes from .background if action == .save { savePending() } } private func savePending() { guard let pending, pending != lastSaved else { return } // nothing new store.save(pending) lastSaved = pending self.pending = nil }}struct PrintingStore: DraftStoring { // a fake store: prints instead of writing to disk func save(_ text: String) { print("saved:", text) }}let saver = DraftSaver(store: PrintingStore())saver.textChanged("Buy mi")saver.textChanged("Buy milk")saver.commit() // saved: Buy milksaver.textChanged("Buy milk") // the same text againsaver.handle(.save) // nothing: already savedsaver.textChanged("Call Ana")saver.handle(.pause) // .inactive: not yetsaver.handle(.save) // saved: Call Anasaver.handle(.save) // nothing pendingprint("done")
pending is a String?: there's something unsaved or there isn't. lastSaved remembers what the
store already has, so writing the same text again doesn't produce another write. commit() saves
on confirmation; handle(_:) saves what's pending only on .save. PrintingStore is a fake
store: instead of writing, it prints, so you see what would have been saved.
To bring it into the lab, copy DraftStoring and DraftSaver (without its SceneAction); wiring it to a view means
keeping the DraftSaver in SwiftUI state, which is part 2.
Expected result:
saved: Buy milksaved: Call Anadone
Common mistakes: saving only on .background (everything is lost if the app crashes first);
saving on every keystroke, which writes hundreds of times; forgetting lastSaved and writing the
same thing on every phase change.
Evaluation criteria: the dependency comes in through the initializer; both ways of saving exist;
the output shows exactly two writes.
Follow-up: what if saving takes several seconds? (beginBackgroundTask(withName:expirationHandler:),
from "Saving"; and saving on every keystroke, with a short wait before
writing, is the "on change" version editors use.)
Exercise 3. An Order's State Machine (Junior/Mid). An order goes through
created → paid → shipped → delivered, and it can be cancelled from created or from paid.
Requirements: the shipped state carries the estimated delivery days as an associated value; an
invalid transition throws an error that says from which state and with which event.
Constraints: no loose Bools for the state; no default that hides combinations.
SolutionEj03OrderStateMachine.swift
enum OrderState { case created case paid case shipped(days: Int) case delivered case cancelled}enum OrderEvent { case pay case ship(days: Int) case deliver case cancel}enum TransitionError: Error { case notAllowed(from: OrderState, event: OrderEvent)}func next(_ state: OrderState, on event: OrderEvent) throws -> OrderState { switch state { // exhaustive on both levels: no default case .created: switch event { case .pay: return .paid case .cancel: return .cancelled case .ship, .deliver: break } case .paid: switch event { case .ship(let days): return .shipped(days: days) case .cancel: return .cancelled case .pay, .deliver: break } case .shipped: switch event { case .deliver: return .delivered case .pay, .ship, .cancel: break } case .delivered, .cancelled: break // final states: nothing moves them } throw TransitionError.notAllowed(from: state, event: event)}func run(_ start: OrderState, _ events: [OrderEvent]) { var state = start do { for event in events { let new = try next(state, on: event) print("\(state) --\(event)--> \(new)") state = new } } catch TransitionError.notAllowed(let from, let event) { print("error: \(from) -> \(event) not allowed") } catch { print("error:", error) }}run(.created, [.pay, .ship(days: 2), .deliver])run(.created, [.cancel])run(.shipped(days: 1), [.cancel])
Two enums, one for the state and one for the event, and a throwing function. The switch is
exhaustive on both levels: in each state, every event appears in a case, valid or invalid (break).
If tomorrow you add a state or an event, the compiler takes you to every place that needs a
decision. Invalid transitions fall through to the throw at the end.
Expected result:
created --pay--> paidpaid --ship(days: 2)--> shipped(days: 2)shipped(days: 2) --deliver--> deliveredcreated --cancel--> cancellederror: shipped(days: 1) -> cancel not allowed
Common mistakes: a default: in the event switch, which treats any new event the same way;
modeling the state with isPaid, isShipped, and isCancelled, which admits an order that's
paid and cancelled at the same time. - Evaluation criteria: exhaustiveness; errors with useful
information; impossible states you can't write. - Follow-up: would throws(TransitionError)
be a good idea here? (It's one of the cases the Swift guide accepts if the error doesn't leave
the module, but the calling code rarely gains anything: it still has to show the error.
The guide recommends not typing it by default.)
Exercise 4. The Cart That Shared Its Coupon (Mid). Predict what this program prints and fix it so
each cart has its own coupon.
Requirements: after the fix, changing the copy's coupon doesn't change the original.
Constraints: keep the usage the same (copy.coupon.discount = 10 has to keep working).
Solution
before and after the fix, with the output of each version:
Before
Ej04CartBefore.swift
final class Coupon { var discount: Int init(discount: Int) { self.discount = discount }}struct Cart { var items: [String] let coupon: Coupon}var original = Cart(items: ["book"], coupon: Coupon(discount: 0))var copy = originalcopy.coupon.discount = 10print("original:", original.coupon.discount, "copy:", copy.coupon.discount)
After
Ej04CartAfter.swift
struct Coupon { // a value now: each cart has its own var discount: Int}struct Cart { var items: [String] var coupon: Coupon // var: changing the coupon changes this cart}var original = Cart(items: ["book"], coupon: Coupon(discount: 0))var copy = originalcopy.coupon.discount = 10print("original:", original.coupon.discount, "copy:", copy.coupon.discount)
Before:
original: 10 copy: 10
After:
original: 0 copy: 10
Cart is a struct, but it held a reference to a class-based Coupon: copying the cart copied the
reference, and both carts shared the coupon. Turning Coupon into a struct gives each cart its own;
the property goes from let to var so the cart's coupon can be modified. The usage doesn't
change.
Common mistakes: thinking var copy = original also copies the object; "fixing" it by creating a
new Coupon by hand on every assignment, which doesn't scale.
Evaluation criteria: explains reference versus value; picks the minimal fix.
Follow-up: when is it actually right for the coupon to be a class? (When it must be shared: a
campaign coupon whose discount changes for every cart at once.)
Exercise 5. Shapes with a Default Description (Mid). Define a Shape protocol with its area and
a default description, and add up the areas of an array of shapes of different types.
Requirements: one type uses the default description and another replaces it.
Constraints: no classes; no String(format:); test values with exact decimals (a 3 × 4 rectangle
and a right triangle with base 4 and height 8).
SolutionEj05Shapes.swift
protocol Shape { var name: String { get } func area() -> Double func describe() -> String // a requirement, so a type can replace it}extension Shape { func describe() -> String { return "\(name): area \(area())" }}struct Rectangle: Shape { let width: Double let height: Double var name: String { "rectangle" } func area() -> Double { width * height }}struct RightTriangle: Shape { let base: Double let height: Double var name: String { "right triangle" } func area() -> Double { base * height / 2 } func describe() -> String { return "\(name), half of \(base) x \(height): area \(area())" }}let shapes: [any Shape] = [Rectangle(width: 3, height: 4), RightTriangle(base: 4, height: 8)]for shape in shapes { print(shape.describe())}let total = shapes.reduce(0.0) { sum, shape in sum + shape.area() }print("total:", total)
describe() is a protocol requirement with a default implementation in the extension: Rectangle
uses it and RightTriangle replaces it with its own. The array is [any Shape] because it mixes
two types. reduce(0.0) walks the array accumulating a sum: it starts at 0.0 and, for each shape,
adds its area.
Expected result:
rectangle: area 12.0right triangle, half of 4.0 x 8.0: area 16.0total: 28.0
Common mistakes: writing describe() only in the extension and not as a protocol requirement;
for each type's implementation to take priority, declare it in the protocol. Also, using
[some Shape], which doesn't compile with different types.
Evaluation criteria: correct use of any; default implementation; value types.
Follow-up: why not [some Shape]? (Because some is a single concrete type, and the array has
two.)
Exercise 6. The Timer That Was Never Freed (Mid/Senior). A Ticker class stores an onTick
closure that increments its counter. Find the retain cycle, break it, and prove the object is freed.
Requirements: show both versions, with the leak and without it, in the same program.
Constraints: the demonstration has to observe the release (with deinit or with a weak reference),
not assume it.
SolutionEj06Ticker.swift
final class Ticker { var ticks = 0 var onTick: (() -> Void)? func startLeaking() { onTick = { self.ticks += 1 } // Ticker -> closure -> Ticker } func start() { onTick = { [weak self] in self?.ticks += 1 } // the way back is weak } deinit { print("deinit Ticker") }}var leaking: Ticker? = Ticker()weak var leakingProbe = leakingleaking?.startLeaking()leaking?.onTick?()leaking = nilprint("without fix:", leakingProbe == nil ? "freed" : "still alive")var fixed: Ticker? = Ticker()weak var fixedProbe = fixedfixed?.start()fixed?.onTick?()fixed = nilprint("with fix:", fixedProbe == nil ? "freed" : "still alive")
The cycle has two arrows: Ticker holds on to the closure (its onTick property) and the closure
holds on to Ticker (it captures self strongly). [weak self] makes the arrow back not count. The
weak probes observe whether each object was freed after letting go of the last variable.
Expected result:
without fix: still alivedeinit Tickerwith fix: freed
Look: deinit Ticker appears only once: the leaking Ticker was never freed.
Common mistakes: using unowned self with no guarantee that the Ticker outlives its closure;
forgetting that the closure is also a reference; "checking" the release by printing a fixed string
instead of observing it.
Evaluation criteria: identifies both arrows of the cycle; proves the release.
Follow-up: what if, instead of a stored closure, it were a concurrency task that never finishes?
(The task holds on to what it captures while it runs: you'll see it in part 2.)
Exercise 7. A Generic LRU Cache (Senior). (LRU, least recently used: the cache evicts
first what has gone unused the longest.) Write LRUCache<Key: Hashable, Value> with a fixed
capacity: when you add an element with the cache full, it evicts one by that rule.
Requirements: get marks the element as used; put returns the evicted key, if there was one.
Constraints: discuss (no need to measure) the cost of get and put; avoid retain cycles between
nodes.
SolutionEj07LRUCache.swift
final class LRUCache<Key: Hashable, Value> { private final class Node { let key: Key var value: Value var next: Node? // strong toward the older end weak var previous: Node? // weak toward the newer end: no cycle init(key: Key, value: Value) { self.key = key self.value = value } } private let capacity: Int private var nodes: [Key: Node] = [:] // O(1) lookup private var head: Node? // most recently used private var tail: Node? // least recently used init(capacity: Int) { self.capacity = capacity } func get(_ key: Key) -> Value? { guard let node = nodes[key] else { return nil } moveToFront(node) return node.value } /// Returns the evicted key, if any. func put(_ key: Key, _ value: Value) -> Key? { if let node = nodes[key] { node.value = value moveToFront(node) return nil } let node = Node(key: key, value: value) nodes[key] = node pushFront(node) guard nodes.count > capacity, let oldest = tail else { return nil } unlink(oldest) nodes[oldest.key] = nil return oldest.key } private func moveToFront(_ node: Node) { unlink(node) pushFront(node) } private func pushFront(_ node: Node) { node.next = head head?.previous = node head = node if tail == nil { tail = node } } private func unlink(_ node: Node) { node.previous?.next = node.next node.next?.previous = node.previous if head === node { head = node.next } if tail === node { tail = node.previous } node.next = nil node.previous = nil }}let cache = LRUCache<String, Int>(capacity: 2)for (key, value) in [("a", 1), ("b", 2), ("c", 3)] { if let evicted = cache.put(key, value) { print("evicted:", evicted) }}print("get b:", cache.get("b") ?? -1)if let evicted = cache.put("d", 4) { print("evicted:", evicted)}print("get c:", cache.get("c") ?? -1)print("get b:", cache.get("b") ?? -1, "get d:", cache.get("d") ?? -1)
A dictionary finds each key's node in constant time (the same whether there are ten elements or
a million), and a doubly linked list (nodes that each point to the next one and the previous
one) keeps the order of use: the head is the most recent and the tail the oldest. Moving a node
to the front or removing the tail is also constant time, so get and put are amortized O(1):
constant time on average.
Each node points to the next one strongly and to the previous one with weak: with both arrows
strong, every pair of neighboring nodes would be a retain cycle. Node is a type declared inside
another one: it exists only as part of LRUCache, and private hides it from outside. LRUCache
is a class and not a struct because it holds class-based nodes: a copied struct would share the
nodes (the lesson of exercise 4). Below, for (key, value) in walks pairs and names each part.
Expected result, with capacity 2: adding a, b, and c evicts a; reading b makes it the most
recent, so adding d evicts c:
A simpler version, with an array of keys in order of use, is acceptable if you justify it: it's
O(n) per operation, and for a cache with few elements that may be enough.
Common mistakes: finding "the oldest" by walking the dictionary, whose order isn't predictable;
forgetting to update head and tail when removing the only node; two strong references between
neighboring nodes.
Evaluation criteria: correctness on the trace; Hashable generic constraint on the key; cycle
between nodes avoided; cost explained.
Follow-up: how would you make it safe if several tasks use it at the same time? (With an actor, which you'll see
in part 2.)
What You Learned
Values and types:let by default, definite initialization, no implicit conversions, and an
overflow that stops the program unless you ask for &+.
Collections: arrays, dictionaries, and sets with value semantics; copy-on-write is how the
library makes them cheap, not a promise; for a stable order, sorted().
Optionals: absence lives in the type; if let, guard let, ??, and ?. before !.
Modeling: structs by default, classes when you need shared identity, enums with associated
values so impossible states can't be written, protocols to depend on capabilities, and generics to
write code once.
Memory: ARC counts strong references; a cycle is a leak you break with weak or unowned, and
an object lives until its last use.
Errors:throws in the signature and try at the call, which lets the error travel on to
the caller until a catch; to handle it on the spot, do/catch, try?, or Result.
The app: you create it in Xcode in Swift 6 mode; it's a set of scenes that go through
.active, .inactive, and .background; you save on every change and flush on the way out;
resources, text, and usage descriptions live in the bundle, and permissions are requested in
context, reading the system's answer.
Interview: eleven questions and seven exercises you can now answer and solve.
What's Next
In part 2: SwiftUI, Networking, Concurrency, and Architecture on iOS
you go from a single word in the simulator to real screens: task lists and forms with SwiftUI, real
tasks from a public API (an internet service that hands data to other programs) fetched with
URLSession, the why behind the main thread and the @Sendables
you saw in "Permissions and Privacy", and an MVVM architecture you can test without a user interface.
Before you move on, a question for you: what app would you like to have on your own iPhone when
you finish the series? Keep it in mind during part 2: every screen you build there is a piece of
that app. And a quick test: if you can explain, without looking, why a closure that uses self can
keep a screen from being freed, you're ready.
Bibliography
The sources were consulted on November 19, 2026, except those marked with another date.
swiftlang/swift, TypeLayout.rst
(how an existential is stored), consulted on November 23, 2026.
I read the "deprecated in a future version" mark on NavigationView in the iOS 27.2 SDK: in
SwiftUI's interface (deprecated: 100000.0) and in usr/include/Availability.h, which defines
that number as an announced deprecation that doesn't produce warnings yet.