Part 2 of 4 of the series "Native iOS Engineering".
You open a to-do app on the subway. A spinner turns while the tasks arrive from the server, and when
the tunnel cuts the signal the app doesn't freeze: it tells you it couldn't refresh. You mark a task as done and the change shows up in the row, in the tab, and on the detail
screen, without anyone having written "update these three labels."
In this part you build the pieces of that screen, one per section, on top of what you learned in
part 1. Nothing
shows up in the code before I explain it, and I ran every example.
answer the 12 interview questions and solve the 8 interview
exercises, from junior to senior level.
Time and paths. Reading all of it takes about two and a half hours. The fast path, about 45
minutes, is four sections: State →
URLSession and Codable → Actors →
Architecture. If you're preparing for an interview, add an optional fifth stop: the
exercises.
The main text is for whoever is starting out; the "The usual mistake" boxes and the real outputs, for
whoever implements; the Going deeper boxes start closed and are for whoever decides.
Going deeper
is iOS for you? A native app is written with the system's own language and
frameworks (on iOS, Swift and SwiftUI); a web app runs in the browser, and a cross-platform one
(React Native, Flutter) is written once for iOS and Android. An iOS developer spends the day
building screens, connecting them to data and to the network, and writing tests;
part 1 tells it in more detail.
For this part a Mac and Xcode, which is free, are enough: you don't need to pay for any account
until you want to publish on the App Store (part 4 explains which account you need and when). If you
like the screen reflecting the data without writing code to keep them in sync, this is for you.
Before You Start
Download the five projects of this part. Every code block says in its title which project and file it
comes from, and when I mention "the package's test," it's in the Tests folder of the zip:
p2-swiftui.zip: views, state, lists, forms, and
navigation.
p2-red.zip: the HTTP client, retries, and cancellation.
how they run and with which settings. A package is a Swift Package
Manager project, Swift's build tool: a folder with a Package.swift that says what gets compiled
and with which settings.
In a package's folder, swift test builds and runs its tests, and swift run <Name> runs one of
the package's programs. The standalone programs of p2-concurrencia and p2-entrevista run with
swift -swift-version 6 File.swift, on macOS or on Linux.
I test the packages that draw interface on macOS, where SwiftUI and Observation exist with the same
design: what they test is logic (a computed string, a rule, how many notifications there are), not
what a screen looks like. They also declare iOS 18 as a platform and build for the iOS simulator.
Projects
Language mode
Default isolation
Approachable Concurrency
p2-swiftui, p2-arquitectura (and the part 4 app)
Swift 6
the main actor
yes
p2-red, p2-concurrencia, p2-entrevista
Swift 6
none
no
They're three concurrency settings that I explain in Actors and the Main Actor.
In the SwiftUI sections they change nothing you see; if you copy a concurrency example into a
project with other settings, the compiler may answer differently.
How I verified the code. I ran everything with Xcode 27.2 (27B52) and Swift 6.4.2 on macOS
27.2.1; the programs, also in Swift 6.4.2's official Docker image, without network. Every output
and every error you see was produced by the tool. There are no performance figures: none were
measured.
In part 4 you put these pieces together in Native Task Manager, a to-do app with SwiftUI,
SwiftData, and an import from a public API.
How SwiftUI Thinks
The problem: the screen and the data drift apart
Picture the app's done-tasks counter: a label with a number and a button that increments it. With
UIKit, iOS's classic interface framework (a framework is a library that organizes your code
around its own: you write the pieces and it decides when to call them), the code creates a label
(UILabel) and a button (UIButton).
Then it registers with addTarget which method to call when the button is tapped, and in that
method it does two things: it changes the number and writes the new text into the label. If you
forget the second one, the screen lies. That style is called imperative: you give the orders, one
by one, for the screen to change.
SwiftUI proposes the declarative style: you describe what the screen looks like for a given value
of the data, and the framework makes sure what you see matches that description when the data
changes. The same counter, in both styles:
Before
p1-ios · SampleApp/CounterViewController.swift
import UIKitfinal class CounterViewController: UIViewController { private var count = 0 let label = UILabel() let button = UIButton(type: .system) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground label.text = "Taps: 0" button.setTitle("Tap", for: .normal) button.addTarget(self, action: #selector(tapped), for: .touchUpInside) let stack = UIStackView(arrangedSubviews: [label, button]) stack.axis = .vertical stack.spacing = 12 stack.translatesAutoresizingMaskIntoConstraints = false view.addSubview(stack) NSLayoutConstraint.activate([ stack.centerXAnchor.constraint(equalTo: view.centerXAnchor), stack.centerYAnchor.constraint(equalTo: view.centerYAnchor), ]) } @objc private func tapped() { count += 1 label.text = "Taps: \(count)" // the data changed: you update the screen by hand }}
After
p2-swiftui · Counter.swift
struct CounterView: View { @State private var taps = 0 // a value the view keeps between updates var body: some View { VStack(spacing: 12) { Text(counterText(taps)) Button("Tap") { taps += 1 } // change the data; SwiftUI recomputes body } }}func counterText(_ taps: Int) -> String { taps == 1 ? "1 tap" : "\(taps) taps"}
The UIKit counter comes from the
part 1
lab (p1-ios, download it), a minimal app that builds and is tested in the simulator. You don't need two of its
pieces to follow along: #selector(tapped) names the method UIKit will call when the button is
tapped, and @objc makes it visible to Objective-C's execution environment, the mechanism UIKit uses to make
those calls.
Notice what's missing from the SwiftUI version: there's no line that writes the text into the label.
The button changes taps, and SwiftUI asks for the description again.
The example uses @State. The @ in front marks a property wrapper or a macro: an attribute
that adds behavior to a property without you writing that code. For now, read it as "a piece of data
the view keeps from one update to the next." It's a preview: I explain it fully in the
state section, and this section makes sense without knowing it.
A view is a value that describes
To SwiftUI, a view is a type that conforms to the View protocol: a struct with a body
property that returns other views. It isn't an object living on screen whose properties you change;
it's a description that's cheap to create and to throw away. CounterView is a struct of a few
bytes: an integer kept by SwiftUI and a body that says "a text and a button, one below the other"
(VStack).
body is a computed property. SwiftUI calls it when it needs the description: the first time the
view appears and, after that, whenever some data the body read changes or the parent view passes it
new values. It compares the new
description with the previous one and applies only the difference to the screen. You don't decide
when body is called; that's why the body has to be a function of the data, with no side effects: no
firing a request or incrementing a counter inside body.
The package's test (Tests/SwiftUIBasicsTests in p2-swiftui.zip) doesn't test the view, which
has nothing to check without a screen: it tests the pure function the body uses. counterText(0) returns "0 taps", counterText(1) returns "1 tap",
and counterText(3), "3 taps". Separating the computed text from the view like this is what lets
you test a screen's logic with tests that take milliseconds.
Identity: when a view is "the same"
If body is recomputed so often, where does the counter's number live? Not in the struct, which is
created anew: SwiftUI keeps it, tied to the view's identity. Identity is how SwiftUI recognizes
that the view in this update is the same as the one in the previous update, even though the struct is
a different one. As long as the identity is preserved, the stored state is preserved; if the identity
changes, SwiftUI considers it a new view and starts with fresh state.
There are two kinds of identity:
Structural: the view's position in the body. The two branches of an if/else are two
different positions, so they're two identities even if both show the same type of view.
Explicit: the one you give with .id(_:) (a modifier, like .opacity(0.5); I explain them in
the next section), or the one the rows of a
list have. Changing the .id value is asking for a new view.
p2-swiftui · Identity.swift
// A view with state of its own: whether its notes are expanded.struct Detail: View { @State private var expanded = false var body: some View { Button(expanded ? "Hide notes" : "Show notes") { expanded.toggle() } }}// Two branches: two different views for SwiftUI. Switching resets Detail's state.struct DetailWithBranches: View { let dimmed: Bool var body: some View { if dimmed { Detail().opacity(0.5) } else { Detail() } }}// One view whose opacity changes: same identity, the state survives.struct DetailWithModifier: View { let dimmed: Bool var body: some View { Detail().opacity(dimmed ? 0.5 : 1) }}// Explicit identity: a new id means a new view, with fresh state.struct DetailForTask: View { let taskNumber: Int var body: some View { Detail().id(taskNumber) }}
Detail keeps whether its notes are expanded. In DetailWithBranches, flipping dimmed from false
to true switches branches: SwiftUI destroys one Detail and creates another, and the notes are
collapsed again. In DetailWithModifier there's a single Detail whose opacity changes: the state
survives. In DetailForTask, each different task number gives a different identity, which is what
you want if task 7's detail must not inherit the state of task 6's detail.
Try it yourself: unzip p2-swiftui.zip and open the folder in Xcode (File › Open…). In the
navigator on the left, choose Sources/SwiftUIBasics/Identity.swift and open the canvas with
Editor › Canvas: it's the preview, which draws the view declared in the file's
#Preview { … } block without running the app.
In it, expand the notes of both Detail views and turn on "Dimmed": the ones in
DetailWithBranches collapse (new view, new state) and the ones in DetailWithModifier stay open.
Counter.swift has its own #Preview: tap "Tap" and the text changes.
The usual mistake: using an if/else to change the look of a view that has state. The
symptom is that what the user had done (some typed text, an open section) "gets lost" when
something that looked cosmetic changes. The consequence is a bug that's hard to reproduce, because
it depends on the order in which the user touched things. If only the look changes, change a
modifier's value and leave the view where it is.
If you come from React
The analogy works as a mental model, not as a description of how things work inside. body resembles
a component's function: it describes the interface from the data and gets called again. Identity
plays the role of React's key: it says which element is which between two updates.
And @State resembles useState: state kept by the framework, tied to identity. The analogy says
nothing about how SwiftUI compares descriptions internally: Apple doesn't document that it uses
React's algorithm.
What to take away: a view describes the screen for some data; SwiftUI keeps its state as long
as its identity doesn't change.
Check what you learned. An if shows Detail() or Detail().opacity(0.5) depending on a
condition. Is Detail's state preserved when the condition changes?
Solution
no. The two branches of the if are two positions in the body, that is, two
identities: when the condition changes, SwiftUI destroys one Detail and creates another with
fresh state. If you write a single Detail().opacity(dimmed ? 0.5 : 1), there's one identity and
the state is preserved.
Going deeper
with Xcode 27, @State stopped being a property wrapper and became a macro, and
its initial value is no longer re-evaluated every time the view's struct is created (iOS 27 release
notes and the State documentation; Apple says that behavior is back-deployed to the systems
aligned with iOS 17).
What changes is the tool, not the system: it depends on building with Xcode
27, not on running on iOS 27. Two consequences: the old advice of delaying the creation of an
expensive model with .task so it isn't instantiated too often is no longer needed, and combining
@State with other property wrappers or macros isn't supported. The packages in this part were
compiled with the macro, because they use Xcode 27.2.
Composition and Modifiers
You paint a label's background yellow, add some padding, and the yellow doesn't reach where you
expected. It isn't a SwiftUI bug: it's the order.
A modifier wraps
A modifier is a method called on a view that returns another view wrapping the first one:
.padding() returns "this view with space around it," .background(.yellow) returns "this view on a
yellow background." Since each one wraps what it receives, order matters; Apple's documentation says
it in those words: the order in which you apply modifiers matters.
p2-swiftui · ModifierOrder.swift
// Each modifier wraps the view it receives and returns a new view.struct PaddingThenBackground: View { var body: some View { Text("Hello") .padding() // 1. a larger view: the text plus space around it .background(.yellow) // 2. the yellow fills that larger view }}struct BackgroundThenPadding: View { var body: some View { Text("Hello") .background(.yellow) // 1. the yellow fills only the text .padding() // 2. transparent space around the yellow text }}
Read it top to bottom, as a chain of wrappers. In PaddingThenBackground, the view is first enlarged
with the padding and then the background of that enlarged view is painted: you see a yellow rectangle
with the text in the middle. In BackgroundThenPadding, the background is painted only behind the
text and the padding stays outside, transparent: you see the text on a tight yellow strip, with empty
space around it.
First .padding() and then .background(.yellow): the background covers the padding.First .background(.yellow) and then .padding(): the padding stays outside the background.
Both screenshots come from the part 1 lab app, which has a screen with these two orders (with the
text in a large size, so it's easier to see); I took them from the simulator.
Small views with simple inputs
When a body grows, you split it into smaller views. A row in the task list is a good candidate: it
receives what it shows as plain properties (let) and doesn't know where the data comes from.
p2-swiftui · ModifierOrder.swift
// A small view with its inputs as plain properties: easy to reuse and to preview.struct TaskRow: View { let title: String let isDone: Bool var body: some View { HStack { Image(systemName: isDone ? "checkmark.circle.fill" : "circle") Text(title) .strikethrough(isDone) Spacer() } .padding(8) .background(alignment: .leading) { // not background(_:alignment:) RoundedRectangle(cornerRadius: 8).fill(.quaternary) } }}
The new pieces: HStack puts its views in a row, Spacer() takes up the leftover space and pushes
the rest to one side, Image(systemName:) draws a system symbol (SF Symbols) by its name,
.strikethrough strikes through the text, and .quaternary is a soft fill color that follows light
or dark mode.
TaskRow stores nothing and decides nothing: given a title and whether it's done, it draws the row.
That makes it reusable (you'll see it again in the list and in the detail) and easy to look at in a
preview. Extracting a subview has no cost you should avoid: a view is a small struct.
The background uses background(alignment:content:), the variant that takes a closure with the
background view. There's another one, background(_:alignment:), which the iOS 27.2 SDK marks as
"deprecated in a future version", with no date, and background(alignment:content:) as the
replacement. That's why the compiler doesn't warn when you use it, and the web documentation shows
the next version, 27.3, as the date.
Try it yourself: in p2-swiftui, open ModifierOrder.swift and the canvas (Editor › Canvas).
You see the two "Hello" texts one below the other, the first inside a yellow rectangle and the
second on a strip that hugs it, and below them a TaskRow marked as done. Swap the order of
.padding() and .background(.yellow) in one of them and watch it change.
The usual mistake: putting a modifier in the wrong place in the chain and looking for the
problem somewhere else. If a background, a border, or a tap area doesn't cover what you expected,
find the modifier that paints or clips in the chain and look at what's above it: it only affects
what it has already wrapped.
What to take away: read the modifiers from top to bottom: each one wraps what came before, so
the order decides the result.
Check what you learned. Why does the background cover the padding in one order and not in the
other?
Solution
because each modifier wraps the view it receives. If the padding goes first, the
background wraps a view that already includes the padding and paints all of it; if the background
goes first, it paints only the text, and the padding is added afterward, on the outside.
State: Who Owns Each Piece of Data
You type a title into a form, rotate the phone, and the field comes back empty. Or you change a task
in the detail and the list keeps showing the old version. Almost every SwiftUI bug you'll debug is of
this kind: ownership bugs. This is the most important section of the part.
The right question
In SwiftUI, state is data that, when it changes, changes what you see. The counter's number is
state; so is the title being typed into a field. Since body is recomputed, state can't live in a
local variable of the body or in a regular property of the struct (which gets created anew): someone
who lives longer than the struct has to keep it.
That's why the useful question isn't "which property wrapper do I use" but who owns this piece of
data. There are four answers, and each has its tool:
Who owns it
Tool
Example
This view, and it's a value
@State
A search box's text, whether a section is open
A parent, which lends it for editing
@Binding
A form's title field that the parent keeps
Something many distant views share
@Environment
The app's preferences
An observable reference model
@Observable, kept in @State by its owner
A task draft with its rules
@State: the view owns it
@State asks SwiftUI to keep a value for you, tied to the view's identity (the one from the previous
section). It's declared private because it belongs to that view and no one else: if someone else
needs to read it, you pass it to them; if someone else needs to change it, you lend them a binding
(the next subsection).
@Binding: the parent lends the data
A binding is read-write access to data that someone else keeps. It isn't a copy: what you write
through the binding changes the original. You get one with the $ prefix on the state ($title is
the binding for title), and the child view declares it with @Binding:
p2-swiftui · Binding.swift
struct NewTaskScreen: View { @State private var title = "" // the parent owns the text var body: some View { TitleField(title: $title) // $title: read-write access, not a copy }}struct TitleField: View { @Binding var title: String // the child edits the parent's value var body: some View { VStack(alignment: .leading) { TextField("Title", text: $title) Text(characterCount(title)).font(.caption) } }}func characterCount(_ text: String, limit: Int = 120) -> String { "\(text.count)/\(limit)"}
NewTaskScreen owns the title. TitleField doesn't know where it comes from: it edits it through the
binding and shows how many characters it has with characterCount, a pure function the package's
test checks (characterCount("Buy milk") returns "8/120"). TextField also receives a binding:
that's how the text field writes straight into the parent's state.
Reference models: the Observation system
When a screen grows, its state stops being a couple of loose values and becomes a model: a draft with
a title, notes, and rules, or a list that's loaded, filtered, and sorted. That model is a class,
because several views have to see the same object
(part 1 explained the difference between value and
reference).
Observation is Swift's system for a class to announce its changes. You turn it on with the
@Observable macro on the class (a macro generates code at compile time: here, the code that
announces each change). Observation exists since iOS 17.
Before that, the way to do it was Combine's ObservableObject protocol (Combine is an older Apple
framework for events that arrive over time): @Published on each property that announces changes
and @StateObject in the owning view. You'll find it in a lot of existing code, so it's worth
recognizing. The two versions of the same editor:
Before
p2-swiftui · LegacyModel.swift
final class LegacyTaskModel: ObservableObject { @Published var title = "" @Published var notes = ""}struct LegacyTaskEditor: View { @StateObject private var model = LegacyTaskModel() // created once, owned here var body: some View { VStack { TextField("Title", text: $model.title) Text(model.title.isEmpty ? "Untitled" : model.title) } }}
After
p2-swiftui · ObservableModel.swift
@Observablefinal class TaskModel { var title = "" var notes = ""}struct TaskEditor: View { @State private var model = TaskModel() // the owner keeps the reference in @State var body: some View { VStack { TitleEditor(model: model) // passed as a plain property… Text(model.title.isEmpty ? "Untitled" : model.title) } }}struct TitleEditor: View { @Bindable var model: TaskModel // …and @Bindable where a binding is needed var body: some View { TextField("Title", text: $model.title) }}
With Observation, @Published and @StateObject go away: the owner keeps the reference in a regular
@State, passes it to its children as a plain property, and the child that needs a binding to a
property of the model declares it with @Bindable (which gives you $model.title).
Try it yourself: open the p2-swiftui folder in Xcode (File › Open…), choose
ObservableModel.swift, and open the canvas (Editor › Canvas). Type into the
"Title" field: the text below changes with every letter, and if you delete everything it says
"Untitled" again. LegacyModel.swift behaves the same on screen; the difference is in the
notifications, which you measure next.
Why Observation: each view tracks only what it reads
The difference that matters isn't syntax. Apple documents that, with Observation, SwiftUI updates a
view only when an observable property that its body read changes; with ObservableObject, any
change to any @Published property invalidates every view observing the object. If a screen only
shows the title, it shouldn't be recomputed when the notes change.
That claim can be measured without a screen. withObservationTracking is the Observation function
that does the same thing SwiftUI does with a body: it runs a closure, records which observable
properties it read, and calls another closure (onChange) right before any of those properties
changes for the first time.
The program reads title inside the tracking, edits notes, and counts the notifications; then it repeats with an edit to title. For the old model, it counts the
notifications from objectWillChange, the publisher (a Combine object you subscribe to in order to
receive notifications) that ObservableObject fires before each change:
p2-swiftui · Tracking.swift
// How many change notifications reach code that read `read`, when `change` runs.func notifications(reading read: () -> Void, after change: () -> Void) -> Int { let counter = ChangeCounter() withObservationTracking(read, onChange: { counter.increment() }) // one-shot change() return counter.value}func observableReport() -> String { let model = TaskModel() let notes = notifications(reading: { _ = model.title }, after: { model.notes = "Bring ID" }) let title = notifications(reading: { _ = model.title }, after: { model.title = "Visit the bank" }) return "@Observable, reading title: notes edit → \(notes), title edit → \(title)"}func legacyReport() -> String { let model = LegacyTaskModel() let counter = ChangeCounter() let subscription = model.objectWillChange.sink { counter.increment() } model.notes = "Bring ID" let notes = counter.value model.title = "Visit the bank" let title = counter.value - notes subscription.cancel() return "ObservableObject: notes edit → \(notes), title edit → \(title)"}
ChangeCounter is a counter that can be incremented from any thread (a line of execution of the
program; I define it in async and await). I explain it in
Sendable.
Try it yourself: in a terminal, in the p2-swiftui folder, run swift run ObservationDemo.
After building, it prints these two lines:
@Observable, reading title: notes edit → 0, title edit → 1ObservableObject: notes edit → 1, title edit → 1
With @Observable, editing notes doesn't notify whoever only read title: zero notifications. With
ObservableObject, editing notes notifies just like editing title. The package's test
(ObservationTrackingTests) asserts
those same numbers, so if a future version of Swift changed the behavior, the test would fail before
the text did.
@Environment: data the whole tree shares
The environment is a set of values SwiftUI passes down the whole view tree, without each
intermediate view having to receive and forward them. The system puts things there like the color
scheme or the scene phase (part 1 used it to read scenePhase); you can put an @Observable model
there with the .environment(_:) modifier, and any view below reads it with
@Environment(Type.self):
p2-swiftui · EnvironmentDemo.swift
@Observablefinal class AppSettings { var showsCompleted = true}struct SettingsRoot: View { @State private var settings = AppSettings() var body: some View { FilterBar() .environment(settings) // every view below can read it }}struct FilterBar: View { @Environment(AppSettings.self) private var settings var body: some View { @Bindable var settings = settings // a binding to a model from the environment Toggle("Show completed", isOn: $settings.showsCompleted) }}
SettingsRoot owns the preferences and publishes them in the environment. FilterBar reads them
without anyone passing them in. To get a binding (the Toggle needs one), it declares a @Bindable
variable inside the body from the environment value, which is what the Bindable documentation
prescribes for models taken from the environment.
The environment is convenient, and that's why it's tempting. Use it for what half the tree really
shares (preferences, the user's session); to pass data from a parent to its child, a property or a
binding is clearer, because it shows up in the view's signature.
What doesn't mix
The two generations coexist, and an app is migrated piece by piece, one model at a time: it can have
ObservableObject models and @Observable models at the same time. What you can't do is use an old
property wrapper with a type that only uses Observation. @StateObject, @ObservedObject, and
@EnvironmentObject require the type to conform to ObservableObject, and the 27.2 SDK compiler
rejects the rest:
@Observablefinal class TaskModel { var title = ""}struct OwnerScreen: View { @StateObject private var model = TaskModel() // an old wrapper… var body: some View { Text(model.title) }}struct ReaderScreen: View { @EnvironmentObject private var model: TaskModel // …with an Observation type var body: some View { Text(model.title) }}
After
errores/OldWrappersWithObservable.swift:11:6: error: generic struct 'StateObject' requires that 'TaskModel' conform to 'ObservableObject' 9 |10 | struct OwnerScreen: View {11 | @StateObject private var model = TaskModel() // an old wrapper… | `- error: generic struct 'StateObject' requires that 'TaskModel' conform to 'ObservableObject'12 | var body: some View { Text(model.title) }13 | }SwiftUI.StateObject:2:67: note: where 'ObjectType' = 'TaskModel'1 | @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)2 | @MainActor @frozen @propertyWrapper @preconcurrency public struct StateObject<ObjectType> : DynamicProperty where ObjectType : ObservableObject { | `- note: where 'ObjectType' = 'TaskModel'3 | @inlinable nonisolated public init(wrappedValue thunk: @autoclosure @escaping () -> ObjectType)4 | @MainActor @preconcurrency public var wrappedValue: ObjectType { get }errores/OldWrappersWithObservable.swift:16:6: error: generic struct 'EnvironmentObject' requires that 'TaskModel' conform to 'ObservableObject'14 |15 | struct ReaderScreen: View {16 | @EnvironmentObject private var model: TaskModel // …with an Observation type | `- error: generic struct 'EnvironmentObject' requires that 'TaskModel' conform to 'ObservableObject'17 | var body: some View { Text(model.title) }18 | }SwiftUI.EnvironmentObject:2:67: note: where 'ObjectType' = 'TaskModel' 1 | @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) 2 | @MainActor @frozen @propertyWrapper @preconcurrency public struct EnvironmentObject<ObjectType> : DynamicProperty where ObjectType : ObservableObject { | `- note: where 'ObjectType' = 'TaskModel' 3 | @MainActor @dynamicMemberLookup @frozen @preconcurrency public struct Wrapper { 4 | @MainActor @preconcurrency public subscript<Subject>(dynamicMember keyPath: ReferenceWritableKeyPath<ObjectType, Subject>) -> Binding<Subject> { get }
The file is in errores/, outside the package, so the rest builds; in the p2-swiftui folder,
xcrun swiftc -swift-version 6 -typecheck errores/OldWrappersWithObservable.swift reproduces this
error.
Apple's migration article says StateObject and EnvironmentObject accept @Observable types; the
27.2 SDK I used doesn't allow it, and here I teach what compiles. When you convert a model, you also
change the property wrappers that use it:
@StateObject → @State in the owning view.
@ObservedObject → a plain property, or @Bindable if the child needs bindings. The
ObservedObject documentation says not to use it with @Observable types, and exercise 11 shows
the same error.
@EnvironmentObject → @Environment(Type.self), with .environment(_:) above, as the
EnvironmentObject documentation indicates.
And the other way around: an ObservableObject kept in @State compiles, but the view doesn't
update when its @Published properties change; for the old model, the owner uses @StateObject.
The usual mistake: creating the model inside body or in a child view's init. Since the body
and the children's structs are recreated on every update, so is the model: every time the parent
changes something, the child receives an empty model and the user loses what they had typed. The
model is created by its owner, once, in a @State (or in @StateObject in older code), and handed
to the others.
Who owns each piece of data decides the tool.
If you come from React
A @Binding resembles passing a child the value and its setter function as props, and the
environment resembles React's Context: both avoid passing data by hand through every level. It's an
analogy of what they're for, not of how they're built.
What to take away: before choosing a property wrapper, ask who owns the data; with Observation, each
view updates only for what it reads.
Check what you learned. A sheet that opens over the list edits the title of a task that lives in
the list. What does the sheet receive?
Solution
a @Binding to the title, if the task is a value the list keeps; or the task's
@Observable model, declared with @Bindable in the sheet to get bindings to its fields. Never a
copy: editing a copy doesn't change the list.
Going deeper
@StateObject guarantees that SwiftUI creates the model only once during the
life of the container that declares it, and creates it again if the view's identity changes: that's
the link between this section and the identity one. With Observation, @State plays that role for
the reference.
SwiftData models, which you'll see in part 3, are
observable too: the macro that declares them adds the Observable conformance, so you read and edit
them in a view with the same rules as this section.
Note: a good point for a break. You're about 30 of the 150 minutes in, and the densest part of
SwiftUI, state, is behind you.
Lists and Forms
A to-do app is, above all, a list and a form. Both look trivial until two tasks have the same name or
the validation starts firing on its own.
Lists: every row needs an identity
List shows scrollable rows, and ForEach generates one view for each element of a collection. For
SwiftUI to know which row is which between one update and the next (the identity from the first
section), ForEach requires the elements to conform to Identifiable. It's a protocol with a single
requirement: an id property whose value tells each element apart and doesn't change while the
element exists.
If the type doesn't conform to the protocol, you pass the id: parameter with a
key path to a property that plays that role: a key path is written \.name and points to a
property of a type without reading it yet (\.self points to the whole element).
p2-swiftui · TaskList.swift
struct TaskItem: Identifiable { let id: UUID // stable: it does not change when the title does var title: String var isDone = false}struct TaskListView: View { @State private var tasks = [ TaskItem(id: UUID(), title: "Buy milk"), TaskItem(id: UUID(), title: "Buy milk"), // same title, different id TaskItem(id: UUID(), title: "Call the bank", isDone: true), ] var body: some View { List { ForEach($tasks) { $task in // identity comes from task.id Toggle(isOn: $task.isDone) { TaskRow(title: task.title, isDone: task.isDone) } } .onDelete { offsets in tasks.remove(atOffsets: offsets) } } }}
Step by step:
TaskItem is a struct with an id of type UUID (a random identifier generated by Foundation,
Apple's base framework, with dates, URLs, networking, and JSON) created when it's built: two tasks
with the same title are still two different tasks.
ForEach($tasks) walks the array with bindings: by naming the closure's parameter $task,
Swift gives you both the binding ($task) and the value (task) of each element, and the Toggle
writes straight into tasks.
.onDelete adds the swipe-to-delete gesture; it receives the positions and removes them from the
array.
The row reuses TaskRow, the view from the composition section.
On iOS, Form (coming up next) and List share a look: Apple documents that a form is displayed as
a grouped list.
Try it yourself: in p2-swiftui, open TaskList.swift and the canvas. You see three rows, two
"Buy milk" and one "Call the bank" struck through. Tap the first one: only that one gets checked,
even though the other has the same name, because each has its own id.
The usual mistake: using id: \.self or id: \.title on data that can repeat. With two tasks
called "Buy milk," both rows have the same identity: SwiftUI may animate the wrong row, delete the
other one, or mix up their state. The symptom usually shows up only with real data, never with test
data.
Forms: validation is a function of the data
A form edits a draft: a value with what the user is typing, which isn't a saved task yet. If the
draft is a struct, the validation rules are a pure function over it, and they're tested without a
screen:
p2-swiftui · TaskForm.swift
enum ValidationError: Equatable { case emptyTitle case titleTooLong var message: String { switch self { case .emptyTitle: "The title can't be empty." case .titleTooLong: "The title can't be longer than \(TaskDraft.maxTitleLength) characters." } }}// What the form edits: a plain value, so the rules can be tested without a screen.struct TaskDraft { static let maxTitleLength = 120 var title = "" var notes = "" var hasDueDate = false var dueDate = Date(timeIntervalSince1970: 1_795_168_800) func validate() -> [ValidationError] { let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) if trimmed.isEmpty { return [.emptyTitle] } if trimmed.count > Self.maxTitleLength { return [.titleTooLong] } return [] }}
The package's test (ValidationTests) asserts three cases: an empty title (or one with only spaces) gives
[.emptyTitle]; one with 121 characters gives [.titleTooLong]; and one with 120 or fewer, with
text, []. With that, the view only has to show the result:
p2-swiftui · TaskForm.swift
struct TaskFormView: View { @State private var draft = TaskDraft() let onSave: (TaskDraft) -> Void private var errors: [ValidationError] { draft.validate() } // derived, never stored var body: some View { Form { Section("Details") { TextField("Title", text: $draft.title) if let error = errors.first, !draft.title.isEmpty { Text(error.message) .font(.footnote) .foregroundStyle(.red) } TextField("Notes", text: $draft.notes, axis: .vertical) } Section("Due date") { Toggle("Has a due date", isOn: $draft.hasDueDate) if draft.hasDueDate { DatePicker("Due", selection: $draft.dueDate, displayedComponents: .date) } } Button("Save") { onSave(draft) } .disabled(!errors.isEmpty) } }}
Three pieces of the form are new. Section groups fields under a heading ("Details", "Due date");
DatePicker lets the user pick a date, and displayedComponents: .date leaves out the time; and
axis: .vertical lets the notes field grow over several lines instead of scrolling in one.
Look at errors: it's a computed property that calls validate() every time the body reads it. It
isn't stored anywhere, so it can never fall out of date with the draft. The message appears under the
field when there's text (so as not to scold someone who hasn't typed anything yet), and the "Save"
button is disabled while there are errors.
Try it yourself: open TaskForm.swift and the canvas. "Save" starts disabled; type a title and
it becomes enabled. Paste a text longer than 120 characters and the red message appears under the
field.
Accessibility: the minimum from the first screen
A list and a form are also used by people who don't see the screen. VoiceOver, iOS's screen reader,
reads each control's text: a Toggle, a TextField, or a Button with text already says what it
is. A button that only has an icon needs a label with .accessibilityLabel("Delete").
Text styles like .font(.footnote) grow with the text size the user chooses (Dynamic Type); a fixed
size in points doesn't. How to check it with the Accessibility Inspector and with the automatic
performAccessibilityAudit audit in a UI test is in
part 3.
This is how it looks in the part 4 app: the error under the field and Save disabled.
The screenshot is from the part 4 app: its code is in the
step 05 zip, the form's.
The rule is the same as in this section, but that app sets the limit at 80 characters and its message
says how many you have; the example here uses 120. If your canvas doesn't show the message at 100
characters, you didn't do anything wrong.
The usual mistake: validating in .onChange(of: draft.title) and storing the result in another
piece of state that, in turn, modifies the draft (for example, by trimming the title). Each change
triggers another one and the view enters an update loop. If a value can be computed from the state,
don't store it: compute it.
What to take away: every row needs a unique, stable id, and every validation error is computed
from the draft, never stored separately.
Check what you learned. Why is ForEach(tasks, id: \.title) fragile?
Solution
because two tasks with the same title would have the same identity. SwiftUI couldn't
tell them apart when inserting, deleting, or reordering, and one row's state could pass to the
other. Identity has to be unique and stable: an id of its own.
Going deeper
if the type is a class and you don't give it an id, Identifiable uses the
object's identity by default, which according to its documentation is only guaranteed unique while
the object exists. If you recreate the objects when reloading the data (when decoding them again,
for example), each load brings new identities and SwiftUI treats every row as new. An id that
comes from the data (the server's, or a persisted UUID) avoids the problem.
Navigation With NavigationStack
You tap a task and its detail opens; you tap "Edit" and a sheet slides up; at the bottom, two tabs.
Part 1
explained those patterns (stack, sheet, tabs, deep link); here's the API that builds them.
The stack as data
NavigationStack is SwiftUI's stack-navigation container: it shows a root view and, on top of it,
the screens that get pushed. Its central idea is that the stack is data: an array (or a
NavigationPath) with the values of the pushed screens. Navigating means changing that data.
The example uses three helper pieces from the same file in the zip, which bring nothing new:
TaskItem.samples (two sample tasks with a fixed id), TaskDetail (the task's row and an "Edit"
button), and TaskEditSheet (a title field and a "Done" button that closes the sheet).
p2-swiftui · Navigation.swift
struct TasksScreen: View { @State private var tasks = TaskItem.samples @State private var path: [TaskItem.ID] = [] // the stack, as data @State private var editing: TaskItem? // non-nil = the sheet is showing var body: some View { NavigationStack(path: $path) { List(tasks) { task in NavigationLink(task.title, value: task.id) // pushes a value, not a view } .navigationTitle("Tasks") .navigationDestination(for: TaskItem.ID.self) { id in // on the List, not inside it if let task = tasks.first(where: { $0.id == id }) { TaskDetail(task: task) { editing = task } } } .toolbar { Button("Open first") { if let first = tasks.first { path = [first.id] } // navigate by changing data } } } .sheet(item: $editing) { task in TaskEditSheet(task: task) } }}struct RootTabs: View { var body: some View { TabView { Tab("Tasks", systemImage: "checklist") { TasksScreen() } Tab("Settings", systemImage: "gear") { SettingsRoot() } } }}
The pieces:
NavigationStack(path: $path) receives a binding to the array of identifiers. If the array is
empty, you see the list; if it has one element, you see that task's detail.
NavigationLink(task.title, value: task.id) doesn't create the destination screen: it pushes a
value.
.navigationDestination(for: TaskItem.ID.self) says which view corresponds to a value of that type.
It's applied to the List, not inside its rows: Apple asks you not to put that modifier inside a
"lazy" container like List or LazyVStack, because their rows are created only when they're
visible and the destination might not be registered when it's needed.
.navigationTitle("Tasks") puts the title in the bar at the top, and .toolbar { } adds buttons to
that bar.
The "Open first" button navigates without touching any link: it assigns path = [first.id]. A deep
link that opens the app on a specific task would do the same.
.sheet(item: $editing) shows a sheet while editing isn't nil, and dismisses it when it goes
back to nil. It requires an Identifiable type, to know whether the sheet to show is the same one
or another.
TabView with Tab organizes the app in tabs. Tab exists since iOS 18; the older form,
tabItem(_:), is marked in the SDK as "deprecated in a future version", with no date (the web
documentation shows the next version, 27.3), and the compiler doesn't warn yet.
Try it yourself: open Navigation.swift and the canvas. You see the "Tasks" tab with two tasks.
Tap "Buy milk": its detail is pushed, with the back button at the top. Tap "Edit": the sheet slides
up. Go back to the list and tap "Open first": you reach the same detail without touching the row.
The "Settings" tab shows the switch from the state section.
Since the path is data, it can also be saved. With an array of encodable values, like the one in this
example, saving the array is enough; NavigationPath is for when the stack mixes different types,
and it has a codable property that, when every pushed value can be encoded, gives you a
representation you can save and restore.
The package's test (NavigationTests) pushes the identifiers of two tasks, saves the path, restores
it, and checks that the restored path has two elements and saves the same way again. You'll see
encoding in detail in the URLSession and Codable section.
The usual mistake: putting .navigationDestination inside a row of the List. It works
sometimes, when the row is on screen, and fails when it isn't: it's the kind of bug that doesn't
show up in the demo and does with a long list.
What to take away: in SwiftUI, navigation is data: an array you change, test, and save like any
other state.
Check what you learned. What do you gain with a path in state over a NavigationLink that
receives the destination view directly?
Solution
navigation becomes data. You can test it (check the array), restore it (save the path
and put it back), manipulate it from code (go back to the root by emptying the array), and build it
from a deep link. With the destination view inside the link, navigation exists only in the
interface.
Going deeper
on an iPhone in landscape, a sheet adapts and is shown as a full-screen
presentation, according to the sheet(item:) documentation; the presentationCompactAdaptation
modifier changes that behavior. And with the 27 SDK, Apple notes in the iOS 27 release notes that
TabView can crash if its selection points to a hidden or unavailable tab: if you hide tabs based
on permissions or configuration, fix the selection before hiding them.
Just Enough HTTP and REST
The task list has to come from somewhere. Before writing a line of networking code in Swift, it's
worth knowing what the app and the server say to each other, because almost every client decision
(what to retry, what to show, when to ask for the session again) comes from there.
A real exchange
HTTP is the protocol a client uses to ask a server for something: the client sends a
request (a method, a path, and some headers) and the server returns a response (a status
code, headers, and, almost always, a body).
An API (application programming interface) is the set of requests a server accepts and responses
it promises. The one in this series is JSONPlaceholder, a public test API with 200 tasks that
responds in JSON, the text format with objects { }, lists [ ], strings, numbers, booleans,
and null.
curl is a terminal program that sends HTTP requests; with -v it shows what goes out and what comes
back. This is the request for task 1 and its response, as curl -v showed them on November 20, 2026, local
time; the server answers in GMT, where it was already the 21st. I removed the diagnostic headers from
the distribution network that sits in front of the server:
The lines with > are what the client sent; the ones with <, what the server answered. GET is the
method, /todos/1 the path, Accept a header that says which format the client accepts, 200 the
status code, and content-type says the body is JSON.
cache-control and etag are for storing the response and validating it later; they're a topic for
part 3. The Latin text in the title is filler: JSONPlaceholder has no real
data. And task 9999, which doesn't exist, responds 404 with a body of {}: remember it, because
later on it breaks a careless client.
Try it yourself: in a terminal on your Mac, run
curl -v -H 'Accept: application/json' https://jsonplaceholder.typicode.com/todos/1. You see the
same lines with > and < (with today's date) and the same body. Change the 1 to 9999 and
you'll see the 404 with {}.
Methods: safe and idempotent
The method states the request's intent. RFC 9110, the specification of HTTP semantics (an RFC is a
specification document from the IETF, the body that standardizes Internet protocols), classifies
methods with two properties that decide what a client may do on its own:
A safe method is one with which the client doesn't request any change on the server: GET, HEAD,
OPTIONS, and TRACE. The server writing a log entry while handling it doesn't make it unsafe: what
counts is what the client asked for.
An idempotent method is one whose intended effect is the same whether it's sent once or several
times: PUT, DELETE, and all the safe ones. The word is about the effect, not the response: a
second DELETE of the same task may respond 404, and it's still idempotent because the task ended
up deleted either way.
POST isn't idempotent: two "create task" POSTs can create two tasks. Neither is PATCH, according to
its own specification (RFC 5789), although a specific API can design its own to be.
Method
Safe
Idempotent
Typical use in the app
GET
yes
yes
Read the list or one task
PUT
no
yes
Replace a whole task
DELETE
no
yes
Delete a task
POST
no
no
Create a task
PATCH
no
no
Change one field (mark it as done)
The practical consequence is in the same RFC: a client shouldn't automatically retry a request with a
non-idempotent method unless it has a way to know the first one had no effect. That rule is the basis
of the retry policy in the Robust Networking section.
Status codes
The code's first digit gives the class of response: 1xx informational, 2xx success, 3xx redirection,
4xx client error, 5xx server error. The ones you'll handle in an app:
Code
What it means
What the client does
200, 201, 204
Success (204: no body)
Use the response
401 Unauthorized
Valid credentials are missing, or the ones you sent don't work
Renew the session once and repeat
403 Forbidden
The server understood and refuses
Don't repeat with the same credentials; explain to the user
404 Not Found
There's no representation of the resource (it doesn't say whether that's temporary)
Treat it as "doesn't exist"
409 Conflict
It clashes with the resource's current state (two edits at once)
Reload and decide
422 Unprocessable Content
The syntax is correct but the content can't be processed
Show the validation error
429 Too Many Requests
Too many requests in a short time (RFC 6585)
Wait; respect Retry-After
503 Service Unavailable
The server can't handle it right now
Wait and retry, if the method allows it
One detail people often get wrong: 401 doesn't mean "no permission." 401 says the request doesn't
carry valid credentials, and RFC 9110 requires the server to send the WWW-Authenticate header.
403 says the server understood the request and refuses (if you sent credentials, they aren't
enough), and the RFC asks you not to repeat the request with the same credentials.
Headers carry the metadata of the request and of the response. Three that this part uses:
Accept (which format the client wants), Authorization (the credentials, for example
Bearer <token>), and Retry-After, which a 503 or a 429 can carry to suggest how long to wait,
either as a number of seconds or as an HTTP date.
What REST is, and what it isn't
REST is an architectural style defined by Roy Fielding in chapter 5 of his doctoral dissertation
(2000).
Its central trait is a uniform interface with four constraints: identification of resources,
manipulation through representations (the JSON or HTML that describes a resource at a given moment),
self-descriptive messages, and hypermedia as the engine of
application state (the response carries the links to what the client can do next). Another
constraint, statelessness, requires each request to contain everything needed to understand it.
An API with clean URLs and JSON isn't REST because of that: JSONPlaceholder doesn't send links to the
possible actions, so I describe it as an "HTTP with JSON, REST-style" API. The distinction matters in
an interview and hardly at all in client code, which works the same way in both cases.
What to take away: before retrying, ask whether the method is idempotent; before decoding, look
at the status code.
Check what you learned. Why shouldn't a client retry on its own a POST that failed with a
timeout?
Solution
because POST isn't idempotent. If the timeout expired after the server processed the
request but before the response arrived, the retry creates a second resource: two identical tasks,
two payments. It's exactly the case that the RFC 9110 rule from
HTTP and REST (under "Methods") keeps out of automatic retries.
Going deeper
RFC 9110 also allows a server to respond 404 instead of 403 so as not to
reveal that a forbidden resource exists; that's why a client shouldn't infer permissions from a
404. And a robust client recognizes a 401 by its code, without depending on the server sending the
WWW-Authenticate header the RFC requires: not every API follows the RFC to the letter.
Two naming facts that come up in interviews: 422's current name is "Unprocessable Content" (the old one,
"Unprocessable Entity," came from WebDAV, an HTTP extension for editing files on a server), and 429
isn't in RFC 9110 but in RFC 6585.
async and await: Just Enough to Talk to the Network
A request takes as long as the network takes: tens of milliseconds with a good signal, seconds on the
subway. Meanwhile the app has to keep responding to the user's finger. Code that waits for a response
can't sit there taking the place of the code that draws the screen.
The problem: waiting without blocking
A thread is a sequence of instructions the operating system runs; a program can have several, and
the system spreads them across the processor's cores. If the thread that serves the interface sits
waiting for the network, the screen freezes. The classic solution was not to wait: pass the function
a closure (the completion handler) that gets called when the response arrives. It works, but when
one load depends on another, the closures nest:
Before
p2-concurrencia (Swift 6, no default isolation) · Callbacks.swift
struct Profile { let name: String}enum LoadError: Error { case notFound}func loadProfile(completion: @escaping (Result<Profile, LoadError>) -> Void) { completion(.success(Profile(name: "Ana")))}func loadTasks(for profile: Profile, completion: @escaping (Result<[String], LoadError>) -> Void) { completion(.success(["Buy milk", "Call the bank", "Book flights"]))}func showDashboard() { loadProfile { profileResult in switch profileResult { case .failure(let error): print("Error:", error) case .success(let profile): print("Profile:", profile.name) loadTasks(for: profile) { tasksResult in switch tasksResult { case .failure(let error): print("Error:", error) case .success(let tasks): print("Tasks:", tasks.count) } } } }}showDashboard()
After
p2-concurrencia (Swift 6, no default isolation) · AsyncAwait.swift
func loadProfile() async throws -> Profile { Profile(name: "Ana")}func loadTasks(for profile: Profile) async throws -> [String] { ["Buy milk", "Call the bank", "Book flights"]}func showDashboard() async { do { let profile = try await loadProfile() // may suspend here print("Profile:", profile.name) let tasks = try await loadTasks(for: profile) // and here print("Tasks:", tasks.count) } catch { print("Error:", error) }}await showDashboard()
Output
Profile: AnaTasks: 3
Both programs print the same thing; the output above is the one from the await version, and the
handler version's is identical (the project checks both). The data is fixed: neither program
touches the network, so the output is always the same.
In the first version, each step lives inside the previous one's closure, the error is handled twice,
and nothing stops you from forgetting to call completion on some path of loadProfile or
loadTasks. In the second, the code reads top to bottom, as if it were synchronous, and a single
do/catch catches the error from either step.
Try it yourself: unzip p2-concurrencia.zip, open a terminal in its folder, and run
swift -swift-version 6 AsyncAwait.swift (on Linux, the same command). It prints Profile: Ana and
Tasks: 3. With Callbacks.swift you see the same. Every program in this part runs this way.
What the two words mean
An asynchronous function is a function marked with async: it can suspend partway through, free
the thread, and continue later. You call it with await, which marks a suspension point: a place
where the function may suspend while it waits. If it can also throw errors, it's declared
async throws and called with try await.
Three details that prevent misunderstandings:
await doesn't stop the thread. While your function is suspended, the thread is free for other work
(for example, drawing the screen).
await marks a possible suspension: if the result is already available, the function may carry
on without suspending.
On resuming, the language doesn't guarantee the function continues on the same thread it was on.
What can be guaranteed is something else, an actor's isolation, which I explain in the section
Actors and the Main Actor.
You can only write await inside asynchronous code. In the program, the await showDashboard() on
the last line is in the file's top-level code (the code outside any function), which Swift allows to
be asynchronous.
In an app, the first asynchronous call is launched by SwiftUI or by your code from a task, which is
the topic of the section Tasks and Structured Concurrency.
In the lesson that follows, the "Execution environment" participant is the part of Swift that, while
the program runs, suspends and resumes functions and spreads the work across threads.
↩ loadTasks(for:) → showDashboard()3 tasksloadTasks(for:) replies to showDashboard(): 3 tasks
Step 6 of 6
Step 6 of 6: It resumes again and prints how many tasks there are. An error from either call would have gone to the same catch.
The function calls an asynchronous function. The await marks a point where it may suspend.
While it waits, showDashboard() suspends. The thread is free: the system can use it to draw the screen or handle other work.
The result arrives. The function resumes, perhaps on another thread: the language doesn't guarantee the same one.
The next line runs, as in synchronous code.
Second suspension point: loading the tasks needs the profile, so it starts afterward.
It resumes again and prints how many tasks there are. An error from either call would have gone to the same catch.
If you come from JavaScript
async and await look a lot like JavaScript's. Two differences matter: in Swift there's no visible
promise and, on resuming, the function may continue on another thread; and Swift adds cooperative
cancellation and structured concurrency, the topic of
Tasks and Structured Concurrency.
Going deeper
in JavaScript an async function returns a Promise, and the code of each page
or worker runs on a single thread, with its own event loop: each ECMAScript agent has its own thread
of execution, and the event loop is defined by the HTML standard, not by the language. That's why
in JavaScript "after the await" is always the same thread, and in Swift there's no such guarantee.
The usual mistake: thinking a function gets faster or "runs in the background" because you
marked it async. async only says the function may suspend. A heavy computation with no
suspension point at all occupies the thread just the same, with or without async. Where an
asynchronous function runs depends on its isolation, which I explain in the actors section.
What to take away:await marks where the function may wait without blocking the thread; the
code reads top to bottom even while it waits.
Check what you learned. Does await mean "the thread stops here"?
Solution
no. await marks a point where the function may suspend; if it suspends, the thread
isn't blocked: it's free for other work, and the function continues later, perhaps on another
thread.
Note: a good point for a break. You're about 55 of the 150 minutes in: you now know what the
client and the server say to each other and how to wait without blocking; what comes next is the complete HTTP client.
URLSession and Codable
The server returns text. Your app works with structs. Between the two there's a boundary where the
text can arrive incomplete, with a different type, or with an error disguised as success, and the
client has to decide in each case what to tell the rest of the app.
From JSON to a struct: Codable
Codable is the union of two Swift protocols: Decodable (a type that can be built from an
external representation, like JSON) and Encodable (one that can be turned into it). If all of a
struct's properties are already Codable (integers, strings, booleans, dates, and arrays of those
types are), the compiler writes the conversion code for you: declaring the conformance is enough.
p2-red · Todo.swift
// The shape of https://jsonplaceholder.typicode.com/todos: four keys, none optional.struct Todo: Codable, Equatable { let userId: Int let id: Int let title: String let completed: Bool}
By default, each property is looked up in the JSON under its own name: userId in Swift reads the
JSON key "userId" (the default strategy is called useDefaultKeys). Since JSONPlaceholder's four
keys match the properties and none is optional, the struct needs nothing else. JSONDecoder, from
Foundation, does the conversion.
The package's test (TodoDecodingTests in p2-red.zip) decodes a file with three real
JSONPlaceholder tasks (numbers 1, 2, and 4) and checks that the first is Todo(userId: 1, id: 1, title: "delectus aut autem", completed: false) and that only one is completed.
If you come from TypeScript: JSON.parse returns any. It checks that the text is valid JSON, but
not that it has the shape you expect, and the compiler doesn't know that shape either (in the React
series that shape was validated separately with Zod, a TypeScript validation library). Decodable checks the shape while decoding:
if a key is missing or a type doesn't match, decoding fails with an error that says where.
The request, step by step
URLSession is the Foundation class that sends HTTP requests. A request is described with a
URLRequest (the URL, the method, the headers, and the timeout, which I explain in the next
section), and the session sends it with data(for:), an asynchronous function that returns the body
and the response. This is the client for the task list:
p2-red · TodosClient.swift
enum APIError: Error { case transport(URLError) // no answer: offline, timeout, DNS… case status(Int) // an answer, but not 2xx case decoding(DecodingError) // a 2xx whose body is not what we expected}struct TodosClient { let session: URLSession // injected: the tests pass one with a fake protocol let baseURL: URL var token: String? = nil func todos() async throws -> [Todo] { // 1. Build the request. var request = URLRequest(url: baseURL.appending(path: "todos")) request.setValue("application/json", forHTTPHeaderField: "Accept") if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } // 2. Send it. A thrown URLError means there was no HTTP answer. let data: Data let response: URLResponse do { (data, response) = try await session.data(for: request) } catch let error as URLError { throw APIError.transport(error) } // 3. Check the status code BEFORE decoding. guard let http = response as? HTTPURLResponse else { throw APIError.transport(URLError(.badServerResponse)) } guard (200..<300).contains(http.statusCode) else { throw APIError.status(http.statusCode) } // 4. Decode. do { return try JSONDecoder().decode([Todo].self, from: data) } catch let error as DecodingError { throw APIError.decoding(error) } }}
The four steps in the comments are the ones every client should have:
Build the request.baseURL.appending(path:) builds the URL; Accept asks for JSON. If
there's a token, it goes in the Authorization header with the Bearer scheme, as RFC 6750
defines it. URLRequest uses GET if you don't give it another method.
Send it.try await session.data(for: request) suspends the function until the complete
response arrives. If it throws a URLError, there was no HTTP response (no connection, timeout
expired, a server name that doesn't exist): the client turns it into .transport.
Look at the status code before decoding.data(for:) returns a general URLResponse; Apple
documents that, for HTTP, the object is an HTTPURLResponse, but you have to cast the type with
as? to read statusCode. A 404 or a 500 are valid responses as far as the session is concerned:
they don't throw anything. If the code isn't 2xx, the client throws .status.
Decode. Only with a 2xx. If the body doesn't have the expected shape, .decoding.
APIError is an enum with associated values, like the ones in part 1. Its three cases answer the
question the rest of the app cares about: was there no response, was there an error response, or was
there a response that can't be understood? Each one is shown to the user differently and treated
differently by the retries.
Note: the catch let error as URLError in step 2 doesn't catch every possible error: whatever
isn't a URLError keeps propagating as is to whoever called todos(). That's intentional, and
you'll need it in the cancellation section.
The session is injected
The client doesn't create its URLSession: it receives it. URLSession.shared works for simple
requests, but Apple recommends a session with its own configuration if you work with caches,
cookies (data the server asks the client to store and send back with each request), authentication,
or custom network protocols. Receiving the session allows both: the app
passes a configured session, and the tests pass one whose configuration only knows a fake
URLProtocol.
A URLProtocol is the Foundation piece that carries out a session's requests; a subclass of your
own, registered as the configuration's only protocol, receives each request and answers whatever the
test tells it, without touching the network. With that fake protocol, the package's tests
(TodosClientTests) assert:
The network responds
The client returns
200 with the three tasks
[Todo] with ids 1, 2, and 4, and the request was a GET to /todos
200, with a token configured
the request carries Authorization: Bearer abc123
404 with body {}
APIError.status(404), not a decoding error
200 with body {}
APIError.decoding with a typeMismatch (an array was expected)
no connection
APIError.transport with the code notConnectedToInternet
The complete fake protocol is in the statement of exercise 10.
Try it yourself: unzip p2-red.zip, open a terminal in its folder, and run swift test. After
building, the last line says 20 tests in 5 test sets passed; each test name shows up with a pass mark.
None of them touches the network.
About the token, a rule that comes from RFC 6750: a Bearer token can be used by anyone who holds it,
without proving it's theirs. That's why it isn't printed in logs or saved in UserDefaults (the app's
store for simple preferences); where it does get stored, the Keychain, is a topic for
part 3.
Each error exit answers a different question: was there a response? was it a success? can it be understood?
Dates: the default strategy isn't ISO 8601
APIs usually send dates as ISO 8601 text ("2026-11-20T10:00:00Z"). JSONDecoder doesn't read them
that way by default: its default date strategy is deferredToDate, which expects Date's own
format: a number of seconds since January 1, 2001 (not since 1970). You have to tell it which one to
use:
p2-concurrencia (Swift 6, no default isolation) · ISO8601Dates.swift
struct Reminder: Decodable { let title: String let due: Date}let json = Data(#"{"title": "Ship v1", "due": "2026-11-20T10:00:00Z"}"#.utf8)// 1. The default date strategy (deferredToDate) expects a number, not text.do { _ = try JSONDecoder().decode(Reminder.self, from: json)} catch DecodingError.typeMismatch(let type, let context) { let path = context.codingPath.map(\.stringValue).joined(separator: ".") print("default strategy: typeMismatch \(type) at \(path)")}// 2. Telling the decoder the dates are ISO 8601 text.let decoder = JSONDecoder()decoder.dateDecodingStrategy = .iso8601let reminder = try decoder.decode(Reminder.self, from: json)print("iso8601 strategy:", reminder.title, Int(reminder.due.timeIntervalSince1970))
default strategy: typeMismatch Double at dueiso8601 strategy: Ship v1 1795168800
#"…"# is a "raw" string literal: the quotes inside it don't need a backslash, which makes it handy
for writing JSON in code.
With the default strategy, the decoder found text where it expected a Double and reported it as a
typeMismatch at the due key. With .iso8601, the date is read correctly; the program prints the
seconds since 1970 (1795168800 is November 20, 2026 at 10:00 UTC) instead of a formatted date,
because how a printed date looks depends on the machine's language and time zone, and the output has
to be the same everywhere.
Reading a decoding error
DecodingError has four cases, and each one carries a context with the key path where it
happened. This program decodes four broken texts and, instead of printing the error's description,
prints the case and the path:
p2-concurrencia (Swift 6, no default isolation) · DecodingErrors.swift
func describe(_ error: DecodingError) -> String { func path(_ context: DecodingError.Context) -> String { let keys = context.codingPath.map(\.stringValue) return keys.isEmpty ? "(root)" : keys.joined(separator: ".") } switch error { case .keyNotFound(let key, _): return "keyNotFound: \(key.stringValue)" case .valueNotFound(_, let context): return "valueNotFound: \(path(context))" case .typeMismatch(_, let context): return "typeMismatch: \(path(context))" case .dataCorrupted(let context): return "dataCorrupted: \(path(context))" @unknown default: return "unknown decoding error" }}let samples = [ #"{"userId": 1, "id": 1, "completed": false}"#, // no title #"{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": null}"#, // null #"{"userId": 1, "id": "1", "title": "delectus aut autem", "completed": false}"#, // id as text #"{"userId": 1, "id": 1, "title": "delectus aut autem""#, // cut off]for sample in samples { do { _ = try JSONDecoder().decode(Todo.self, from: Data(sample.utf8)) print("decoded") } catch let error as DecodingError { print(describe(error)) }}
typeMismatch: the key is there but the type doesn't match (id arrived as text).
dataCorrupted: the JSON isn't even valid (it's cut off), and the path is empty.
The second case deserves attention. The DecodingError.valueNotFound documentation describes it
as the error for finding null where a non-optional value was expected. But with Swift 6.4.2,
JSONDecoder reported a null in the non-optional Bool as typeMismatch, on Linux and on macOS
(the p2-red test nullInANonOptionalIsATypeMismatch asserts it on macOS, which uses the same Foundation as iOS). Your code shouldn't
depend on which of the two cases arrives: treat them the same.
The usual mistake: decoding without looking at the status code. A GET /todos/9999 to
JSONPlaceholder responds 404 with the body {}. If the client decodes directly, the error it sees
is "expected an array and got an object," and someone spends an hour hunting for a format problem
that was really a 404.
The second usual mistake is showing or logging a DecodingError's localizedDescription: its text
changes between platforms and doesn't say which key failed. Log the case and the path.
What to take away: a client separates three questions, was there a response?, was it a
success?, can it be understood?, and looks at the status code before decoding.
Check what you learned. The API returns "due": "2026-11-20T10:00:00Z" and your due: Date
property fails to decode. Why, and how do you fix it?
Solution
because, unless you ask it to, JSONDecoder doesn't read ISO 8601 text (the reason is
in Dates). One line is missing before decoding:
decoder.dateDecodingStrategy = .iso8601.
Going deeper
there are two ways to handle Swift names that don't match the JSON's. A
CodingKeys enumeration inside the type gives the exact name of each key; the
keyDecodingStrategy = .convertFromSnakeCase strategy turns due_date into dueDate for the whole
decoder. The first tolerates exceptions; the second is convenient if the API is consistent.
Another design decision: Todo describes the shape of the server's JSON (a DTO, which I define in
the architecture section), and the part 4 app has its own model, TaskItem.
Keeping them separate lets the server change without breaking the local database, at the cost of
writing the mapping.
Finally, Swift 6 lets you declare the type of error a function throws (throws(APIError)), but the
language guide recommends against it except in specific cases; that's why todos() uses throws.
Robust Networking: Timeouts, Retries, and Pagination
The client from the previous section works with a good signal. On the subway, the same request can
hang, the server can answer "not now" with a 503, and the list can have thousands of tasks. Three
decisions separate a demo client from one that holds up: how long to wait, what to retry, and how to
ask in pieces.
How long to wait
A timeout is the limit after which the client considers a request failed. URLSession has two,
and setting the wrong one is a classic mistake:
Setting
What it measures
Default value
URLRequest.timeoutInterval and the configuration's timeoutIntervalForRequest
Inactivity: time without receiving data. The timer resets every time data arrives
60 seconds
The configuration's timeoutIntervalForResource
The total: how long the whole transfer can take
7 days
When the inactivity timeout expires, the session throws a URLError with the code .timedOut. The
key is the first row: a timeoutInterval of 30 seconds doesn't cut off a five-minute download that
keeps receiving data nonstop, and it doesn't protect you from a slow but steady server.
If you need a total limit, that's timeoutIntervalForResource, which you set on the
URLSessionConfiguration you create the session with.
What to retry
Retrying is for transient failures: an expired timeout, a 503 from the server, a 429 for too many
requests. It doesn't help, and it does harm, for a 400 or a 404: the second time will fail the same
way. And, by RFC 9110's rule from the HTTP section, only idempotent methods are
retried automatically.
Between attempts you wait, and the wait grows: 1 second, 2, 4. That's called exponential backoff,
and it keeps a thousand clients from hammering at once a server that's already in trouble. If the
server sent Retry-After, its value wins.
Actually waiting in a test would make it slow. That's why the waiting is injected, just like the
session. Before the code, what it's missing: it's a teaching version, with no random variation in the
wait, no cap on a very long Retry-After, and no retry for URLError codes other than the timeout;
the box below the table goes into detail.
p2-red · RetryPolicy.swift
// Waiting is injected: the app waits for real, the tests only write down how long.protocol Sleeper { func sleep(seconds: Int) async throws}struct TaskSleeper: Sleeper { func sleep(seconds: Int) async throws { try await Task.sleep(for: .seconds(seconds)) // waits without blocking the thread }}struct RetryPolicy { var maxAttempts = 3 var baseDelay = 1 // seconds: 1, 2, 4… let sleeper: any Sleeper var now: () -> Date = Date.init func send(_ request: URLRequest, with session: URLSession) async throws -> (Data, HTTPURLResponse) { var attempt = 1 while true { do { let (data, response) = try await session.data(for: request) guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) } let busy = http.statusCode == 429 || http.statusCode == 503 guard busy, isIdempotent(request), attempt < maxAttempts else { return (data, http) } try await sleeper.sleep(seconds: delay(after: attempt, response: http)) } catch let error as URLError where error.code == .timedOut { guard isIdempotent(request), attempt < maxAttempts else { throw error } try await sleeper.sleep(seconds: delay(after: attempt, response: nil)) } attempt += 1 } } // RFC 9110: only idempotent methods may be retried automatically. POST and PATCH are not. func isIdempotent(_ request: URLRequest) -> Bool { ["GET", "HEAD", "OPTIONS", "TRACE", "PUT", "DELETE"].contains(request.httpMethod ?? "GET") } // The server's Retry-After wins; otherwise exponential backoff. func delay(after attempt: Int, response: HTTPURLResponse?) -> Int { if let value = response?.value(forHTTPHeaderField: "Retry-After"), let seconds = secondsToWait(retryAfter: value, now: now()) { return seconds } return baseDelay << (attempt - 1) }}
Sleeper is a protocol with a single function. The real implementation, TaskSleeper, uses
Task.sleep(for:): for now, read it as "wait without blocking the thread"; tasks are explained in
the next section, and this one makes sense without them. baseDelay << (attempt - 1) shifts the bits
(the zeros and ones the number is stored as) to the left, and each position doubles the number: 1, 2, 4.
The tests use another implementation that doesn't wait: it only writes down how many seconds it was
asked for. With it and with the fake network protocol, the package's tests (RetryPolicyTests)
assert:
The network responds
Method
Attempts
Recorded waits
503, 503, 200
GET
3
[1, 2]
503 (and then 200)
POST
1, returns the 503
none
429 with Retry-After: 5, 200
GET
2
[5]
503 with Retry-After: Fri, 20 Nov 2026 10:02:00 GMT, 200, with "now" = 10:00:00
GET
2
[120]
timeout expired, 200
GET
2
[1]
503, 503, 503
GET
3, returns the last 503
[1, 2]
Going deeper
what a code review would ask of this policy:
Random variation in the wait (what's usually called jitter): if a thousand clients fail at
once and all of them wait 1, 2, and 4 seconds, they arrive together again.
A cap on the wait the server asks for: a Retry-After of one hour would make it wait an hour.
More retryable errors: on the subway you also get networkConnectionLost and
notConnectedToInternet, not only an expired timeout.
Knowing that the RFC doesn't prescribe multiple attempts: it asks you not to automatically retry
an automatic retry that failed. Exponential backoff guided by Retry-After is common practice,
not a standard.
Retry-After accepts two formats, seconds or an HTTP date, and the client has to accept both. The
parser, on its own. It's a teaching version too: it accepts the current HTTP date format, when RFC
9110 asks you to accept the three it defines, and it creates a formatter on every call.
p2-concurrencia (Swift 6, no default isolation) · RetryAfter.swift
// Retry-After is either a number of seconds or an HTTP date (RFC 9110, 10.2.3).func secondsToWait(retryAfter value: String, now: Date) -> Int? { if let seconds = Int(value), seconds >= 0 { return seconds } let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") // HTTP dates are always English formatter.timeZone = TimeZone(identifier: "GMT") formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss 'GMT'" guard let date = formatter.date(from: value) else { return nil } return max(0, Int(date.timeIntervalSince(now).rounded(.up)))}// A fixed "now" keeps the output the same on every run: 2026-11-20 10:00:00 UTC.let now = Date(timeIntervalSince1970: 1_795_168_800)print(secondsToWait(retryAfter: "120", now: now) ?? -1)print(secondsToWait(retryAfter: "Fri, 20 Nov 2026 10:02:30 GMT", now: now) ?? -1)print(secondsToWait(retryAfter: "soon", now: now) ?? -1)
120150-1
HTTP dates are always written in English and in GMT, which is why the formatter pins the
en_US_POSIX locale and the time zone: that way the result doesn't depend on how the device is
configured. "Now" is fixed so the output is the same on every run; a value that can't be understood
returns nil (printed here as -1), and the policy falls back to exponential backoff.
Try it yourself: in p2-concurrencia, swift -swift-version 6 RetryAfter.swift prints 120,
150, and -1. In p2-red, swift test --filter RetryPolicyTests runs the six tests in the
table.
Asking in pieces: pagination
Pagination means requesting a large collection in pieces, one page at a time. No IETF standard
defines it. The closest thing is RFC 8288's Link header, which carries typed links to other
representations, and the registered relations next, prev, first, and last. The common forms,
which are practice and not a standard, are three:
By page number (?page=2): the simplest.
By offset (?offset=40&limit=20): how many to skip and how many to fetch.
By cursor (?after=abc): the server returns an opaque marker of where the list left off, and
the client sends it back.
JSONPlaceholder doesn't document pagination, but its server responds to ?_page=1&_limit=2 with a
Link header and with X-Total-Count: 200 (observed on November 19 and 20, 2026).
Since it isn't documented, it isn't a contract: the example reads the header the server responded
with, stored in the program, and doesn't depend on the server continuing to respond that way. The
parser covers the simple form of the header, the one this server sends; RFC 8288 allows more
parameters and quoting that this code doesn't handle.
p2-concurrencia (Swift 6, no default isolation) · LinkPagination.swift
// The Link header that JSONPlaceholder sent for /todos?_page=1&_limit=2// (observed on 2026-11-20; the site does not document it).let header = #"<https://jsonplaceholder.typicode.com/todos?_page=1&_limit=2>; rel="first", <https://jsonplaceholder.typicode.com/todos?_page=2&_limit=2>; rel="next", <https://jsonplaceholder.typicode.com/todos?_page=100&_limit=2>; rel="last""#// Returns rel → URL text, for the simple form of the header (RFC 8288).func links(in header: String) -> [String: String] { var result: [String: String] = [:] for part in header.split(separator: ",") { let pieces = part.split(separator: ";").map { $0.trimmingCharacters(in: .whitespaces) } guard let target = pieces.first, target.hasPrefix("<"), target.hasSuffix(">") else { continue } for parameter in pieces.dropFirst() where parameter.hasPrefix("rel=") { let rel = parameter.dropFirst("rel=".count).trimmingCharacters(in: CharacterSet(charactersIn: "\"")) result[rel] = String(target.dropFirst().dropLast()) } } return result}let found = links(in: header)for rel in found.keys.sorted() { print("\(rel): \(found[rel]!)")}
The program sorts the relations before printing them because the order of a Swift dictionary isn't
defined (part 1 explained it with Set and Dictionary). An app would use
next to request the next page when the user reaches the end of the list, and stop requesting when
there's no next.
The usual mistake: retrying in a loop with no limit and no wait. With a bad signal, the app
sends dozens of requests per second, drains the battery, and, if the method wasn't idempotent, can
duplicate data. Every retry needs a maximum, a wait that grows, and a list of what gets retried.
What to take away: a request's timeout measures inactivity, not the total; and every retry
needs a maximum, a growing wait, and a method that can be repeated.
Check what you learned. A slow but steady 10-minute download has timeoutInterval = 60. Does it
fail?
Solution
no. With data arriving nonstop, 60 seconds without receiving anything never go by, and
that's all timeoutInterval watches (the table in How long to wait). Ten
minutes is far from the total limit, timeoutIntervalForResource, 7 days by default.
Going deeper
offset or cursor isn't a matter of taste when the list changes while you walk
through it. With an offset, if someone inserts a task at the beginning between page 1 and page 2,
everything shifts by one and page 2 repeats a task; if someone deletes one, a task gets skipped.
With a cursor that points to an element, the next page starts after that element, whatever gets
inserted before it. Part 3 comes back to this with a real
case.
Note: a good point for a break. You're about 80 of the 150 minutes in, and the network client is
complete; what comes next is Swift concurrency, from tasks to actors.
Tasks and Structured Concurrency
The home screen needs the profile and the task list. Requesting them one after the other adds up the
two times; requesting them at once costs as long as the slowest one takes. And if the user leaves the
screen before they arrive, both requests should stop working for no one.
What a task is
A task is Swift's unit of asynchronous work: something that runs, can suspend at its awaits,
and finishes with a result or an error. All asynchronous code runs inside a task. There are two ways
to create them, and the difference is the most important idea in this section:
Child tasks, with async let or with a task group: they're tied to the scope (the block of
code) that created them. That's structured concurrency: a child task can't outlive its scope,
just as a local variable doesn't outlive its function.
Unstructured tasks, with Task { }: they start running when you create them and keep going
even if you drop the reference it returns. They're for starting asynchronous work from code that
isn't asynchronous (a button's action) and for holding on to work you want to be able to cancel
later.
Two things at once: async let
p2-concurrencia (Swift 6, no default isolation) · AsyncLet.swift
func loadDashboard() async throws -> String { async let profile = loadProfile() // starts now, as a child task async let tasks = loadTasks() // starts now too, without waiting for the first let (p, t) = try await (profile, tasks) // waits for both return "\(p.name) has \(t.count) tasks"}
Ana has 3 tasks
Here the two loads are independent: loadTasks() doesn't need the profile, unlike loadTasks(for:)
in the previous section. If one depends on the other's result, they can't be launched at the same
time.
async let profile = loadProfile() launches the load as a child task and moves on to the next
line without waiting. The second load starts too. The try await (profile, tasks) waits for both. If
you leave the function without awaiting an async let (because of an early return or because
another line threw an error), Swift cancels it and waits for it to finish before leaving: no orphaned
work is left behind.
Try it yourself: in p2-concurrencia, swift -swift-version 6 AsyncLet.swift prints
Ana has 3 tasks, and swift -swift-version 6 TaskGroupOrder.swift prints the list from the next
subsection. Run them several times: the output doesn't change.
N things at once: task groups
async let is for when you know how many things you launch at the time you write the code. For a
number known only at run time (downloading the N images of a list) there's the task group:
withTaskGroup or, if the children can throw errors, withThrowingTaskGroup.
p2-concurrencia (Swift 6, no default isolation) · TaskGroupOrder.swift
// A fake download: nothing touches the network. The longer names "take"// longer, so the children finish in a different order than they started.func download(_ name: String) async throws -> String { for _ in 0..<(name.count * 10) { await Task.yield() } return name.uppercased()}func downloadAll(_ names: [String]) async throws -> [String] { try await withThrowingTaskGroup(of: (Int, String).self) { group in for (index, name) in names.enumerated() { group.addTask { (index, try await download(name)) // each child returns its position } } var results = [String?](repeating: nil, count: names.count) for try await (index, value) in group { // in order of completion results[index] = value } return results.compactMap { $0 } // back in order of input }}print(try await downloadAll(["photos", "a", "notes", "contacts"]))
["PHOTOS", "A", "NOTES", "CONTACTS"]
Task.yield() gives the turn to other tasks; here, repeating it more times for the long names
simulates a slower download.
A group's children don't finish in any guaranteed order. In the program, the fake download of
"a" finishes before the one for "photos", and the for try await loop receives the results in
order of arrival. That's why each child returns its position along with the value, and the result
is put back in place by index: that way the output always respects the input order. If a child throws
an error, the group cancels the others before leaving and the error propagates to whoever called
downloadAll.
Child tasks live inside the scope that created them; cancelling the root cancels the whole tree.
Cancelling: cancellation is cooperative
Cancelling a task doesn't stop it by force. It marks the task as cancelled and lets its code notice
and decide where to stop: that's cooperative cancellation.
The code checks for it in two ways: try Task.checkCancellation(), which throws CancellationError
if the task is cancelled, or the Task.isCancelled property, which returns a Boolean. Many system
functions already check it internally; Task.sleep, for example, finishes early by throwing
CancellationError.
Before the code, a new piece: the program uses an AsyncStream (a sequence of values that arrive
over time and that you walk with for await) so the "user" cancels exactly when item 3 starts, and
not depending on how long each thing takes on the machine.
p2-concurrencia (Swift 6, no default isolation) · Cancellation.swift
// Item 3 is the slow one: it waits until someone cancels the task.func download(_ item: Int) async throws { if item == 3 { try await Task.sleep(for: .seconds(60)) // throws CancellationError when cancelled }}func importAll(_ items: [Int], started: AsyncStream<Int>.Continuation) async throws -> [Int] { var imported: [Int] = [] do { for item in items { try Task.checkCancellation() // cooperative: the code decides where to stop started.yield(item) try await download(item) imported.append(item) } } catch is CancellationError { print("cancelled after importing \(imported)") // what was done stays done throw CancellationError() } return imported}let (startedItems, started) = AsyncStream.makeStream(of: Int.self)let job = Task { try await importAll([1, 2, 3, 4, 5], started: started)}// The "user" taps Cancel as soon as item 3 starts.for await item in startedItems where item == 3 { print("item 3 started, cancelling") job.cancel() break}let result = await job.resultprint(result)
item 3 started, cancellingcancelled after importing [1, 2]failure(Swift.CancellationError())
The program's "user" cancels as soon as item 3, the slow one, starts. The wait in download(3)
throws CancellationError, importAll reports what it had done and rethrows, and whoever awaits the
result receives a failure: job.result is a Result, the success-or-failure enum from
part 1.
Notice what does not happen: items 1 and 2 stay imported. Cancellation undoes nothing; if your operation needs
to be all or nothing, you have to program that yourself. And once cancelled, a task can't be
"uncancelled."
Cancelling a request in flight
Cancelling the task that's awaiting a data(for:) also cancels the network request. With p2-red's
fake network protocol set up to never respond, the session throws URLError with the code
.cancelled, not CancellationError, whether the task is cancelled during the load or before the
request starts.
That's why the client from URLSession and Codable, which wraps every URLError in
.transport, turns a cancellation into something that looks like a network failure. The fix is to
recognize both forms:
p2-red · Cancellation.swift
extension APIError { // Cancelling the task cancels the request in flight. URLSession reports it // as URLError.cancelled, not as CancellationError (measured in the tests), // so code that shows errors to the user should check both. static func isCancellation(_ error: any Error) -> Bool { if error is CancellationError { return true } if case .transport(let urlError)? = error as? APIError { return urlError.code == .cancelled } if let urlError = error as? URLError { return urlError.code == .cancelled } return false }}func loadTodosUntilCancelled(_ client: TodosClient) async -> String { let load = Task { try await client.todos() } // …the user leaves the screen before the answer arrives: load.cancel() switch await load.result { case .success(let todos): return "loaded \(todos.count)" case .failure(let error) where APIError.isCancellation(error): return "cancelled, nothing to show" case .failure(let error): return "failed: \(error)" }}
The tests assert what was measured: cancelling during the load makes todos() fail with an
APIError.transport whose code is .cancelled; the unwrapped data(for:) throws a URLError with
.cancelled and not CancellationError; and loadTodosUntilCancelled returns "cancelled, nothing to show". A screen that shows "Couldn't connect" when the user only moved to another tab is a bug
the user does see.
Task { } and Task.detached
Task { } inherits three things from the context that creates it: its isolation (which actor it runs
on, the topic of the next section; inside an actor's method, only if the closure uses self), its priority, and the task-local values (values a task carries
with it that all its children see, like an identifier for following an operation in the logs).
Task.detached inherits none of them.
That's why Task.detached isn't the way to "send something to
the background": it loses the priority and the context, and it forces you to think again about which
isolation it runs in. Since Swift 6.2 there's an explicit way to say "this function runs off its
caller's actor," which I show you in the actors section.
The usual mistake: writing [weak self] by reflex in every Task { }. The Task
documentation explains that the task releases its closure (and what it captures) when it finishes,
so a task that finishes rarely needs a weak reference. While it runs, it does retain self: the
exception is long-running or infinite tasks (a loop listening for updates), which would keep the
object alive forever.
There, yes, [weak self] or, better, keep the task and cancel it when the
owner goes away. The symptom, an object that isn't released, shows up in Xcode's Memory Graph
Debugger, which part 3 teaches you to use.
What to take away: child tasks live inside their scope and are cancelled with it; cancelling is
asking them to stop, and the code decides where.
Check what you learned. You leave a function with an async let you never awaited. What happens
to that task?
Solution
it isn't left orphaned: it's this section's async let rule. A child task never
outlives the scope that created it.
Going deeper
Swift 6.4 added cancellation shields (withTaskCancellationShield, SE-0504): a
block of code that runs as if the task weren't cancelled, useful for cleanup that has to finish.
Inside an active shield, Task.isCancelled can return false even if the task was cancelled from
outside, so a function that checks for cancellation can't assume it will always see the flag. The
same version allows await inside defer (SE-0493): the asynchronous code in the defer is
awaited and finishes before leaving the scope.
Actors and the Main Actor
Two withdrawals of 100 each arrive at the same time at the same account, and the account holds 100.
If both parts of the program read the balance, see 100, and subtract, the account ends up at −100.
With tasks running at the same time, someone has to decide who touches the state and when.
An actor protects its state
An actor is a reference type, like a class, that lets only one task at a time access its mutable
state. You declare it with actor instead of class.
From outside, every access to its properties and methods goes through await, because another task
may be inside and you may have to wait your turn. There are two exceptions, which don't touch the
mutable state: whatever is marked nonisolated and, within the same module, let constants of types
that can be shared.
Inside the actor, code accesses its state without await: it already has the turn. That rule of "who can touch this state and from where" is called isolation: an
actor's state is isolated in it.
By default, an actor doesn't have a thread of its own: its jobs run on the pool of threads that all of
Swift concurrency shares, one at a time.
Reentrancy: what an actor doesn't guarantee
An actor guarantees that two tasks don't touch its state at the same instant. It doesn't guarantee
that nobody touches it while your method is waiting. When an actor method reaches an await, it
suspends and gives up the turn, and another task can come in and change the state before the first
one continues. That's called reentrancy.
Swift's actors are reentrant on purpose: if they weren't, an actor waiting on the network would block everyone else for seconds.
The program forces that interleaving with a meeting point (Rendezvous, a helper actor in the file
that holds each withdrawal until both have arrived), so the result is the same on every run. In an
app, the interleaving depends on timing: it may never happen in your tests and happen in production.
p2-concurrencia (Swift 6, no default isolation) · ActorReentrancy.swift
actor Account { private(set) var balance: Int private(set) var accepted = 0 private let audit: Rendezvous // stands for any await: a log, a server call init(balance: Int, audit: Rendezvous) { self.balance = balance self.audit = audit } // Naive: checks, suspends, then trusts the old check. func withdrawNaive(_ amount: Int) async { guard balance >= amount else { return } await audit.arrive() // another withdrawal can run here balance -= amount accepted += 1 } // Fixed: checks again after every suspension. func withdraw(_ amount: Int) async { guard balance >= amount else { return } await audit.arrive() guard balance >= amount else { return } // the state may have changed balance -= amount accepted += 1 }}func twoWithdrawals(naive: Bool) async -> String { let account = Account(balance: 100, audit: Rendezvous(expected: 2)) await withTaskGroup(of: Void.self) { group in for _ in 1...2 { group.addTask { if naive { await account.withdrawNaive(100) } else { await account.withdraw(100) } } } } return "accepted withdrawals: \(await account.accepted), balance: \(await account.balance)"}print("naive:", await twoWithdrawals(naive: true))print("fixed:", await twoWithdrawals(naive: false))
withdrawNaive checks the balance, suspends at await audit.arrive() and, on returning, subtracts
trusting the earlier check. Both withdrawals passed the check with a balance of 100 before either one
subtracted: both are accepted and the account ends up at −100. It isn't a data race (there were never
two accesses at the same time; the actor prevents that), it's a logic bug.
withdraw checks again after the await: the second withdrawal finds a balance of 0 and is
rejected. The general rule: anything you read before an await may have changed after it.
Revalidate, or make the change before suspending.
Try it yourself: in p2-concurrencia, swift -swift-version 6 ActorReentrancy.swift prints the
two lines above on every run.
Going deeper
the meeting point.Rendezvous stores each call that arrives in a
continuation (an object that resumes a suspended function when someone asks it to) and, once the
expected ones have arrived, resumes them all. That's what guarantees both withdrawals are suspended
at the same time:
p2-concurrencia (Swift 6, no default isolation) · ActorReentrancy.swift
actor Rendezvous { private let expected: Int private var waiting: [CheckedContinuation<Void, Never>] = [] init(expected: Int) { self.expected = expected } func arrive() async { await withCheckedContinuation { continuation in waiting.append(continuation) if waiting.count == expected { waiting.forEach { $0.resume() } waiting.removeAll() } } }}
If you come from Java
A Java synchronized method takes the object's monitor before running and holds it until it returns,
also while it blocks on I/O or in Thread.sleep: no one else gets in (only wait() releases it). An
actor doesn't hold a thread while it waits; that's why it can be reentrant at every await, and the
"check, wait, act" pattern needs revalidation, as in Java after a wait().
The main actor
MainActor is a global actor, unique in the program, whose executor (what decides which thread an
actor's jobs run on) is equivalent to the main queue, the job queue of the main thread: whatever is
isolated to the main actor is run by the main thread, the one that serves the interface. You mark it
with the @MainActor attribute on a function, a property, or a whole type.
The main actor and the main thread are closely related, but they aren't the same thing. The language
guide puts it this way: your code interacts with the actor, and the thread is a lower-level detail.
The practical difference: the compiler reasons about isolation (this code is on the main actor, that
code isn't), not about threads, and isolation is what the Swift 6 mode guarantees you.
p2-concurrencia (Swift 6, no default isolation) · MainActorScreen.swift
@MainActorfinal class DashboardScreen { private(set) var title = "Loading…" func show(_ count: Int) { title = "\(count) tasks" }}// nonisolated: it does not belong to any actor.func countTasks() async -> Int { ["Buy milk", "Call the bank", "Book flights"].count}@MainActorfunc refresh(_ screen: DashboardScreen) async { let count = await countTasks() // leaves the main actor and comes back screen.show(count) // back on the main actor: synchronous access print(screen.title)}await refresh(DashboardScreen())
3 tasks
DashboardScreen is isolated to the main actor; countTasks doesn't belong to any actor
(nonisolated). refresh is on the main actor, calls countTasks with await, comes back, and
writes to the screen without await, because it's already on the same actor. If a function that
isn't on the main actor tries to write directly to an isolated property, the compiler rejects it:
Before
p2-concurrencia (Swift 6, no default isolation) · errores/MainActorWithoutAwait.swift
errores/MainActorWithoutAwait.swift:8:12: error: main actor-isolated property 'title' can not be mutated from a nonisolated context 1 | @MainActor 2 | final class DashboardScreen { 3 | var title = "Loading…" | `- note: mutation of this property is only permitted within the actor 4 | } 5 | 7 | func rename(_ screen: DashboardScreen) { // nonisolated | `- note: add '@MainActor' to make global function 'rename' part of global actor 'MainActor' 8 | screen.title = "Ready" // main-actor state, no await | `- error: main actor-isolated property 'title' can not be mutated from a nonisolated context 9 | }
The message says what's isolated (title, on the main actor), where the attempt came from (a
nonisolated context), and proposes the most direct fix: marking the function with @MainActor. The
alternatives are making it async and writing through a main-actor method with await.
Where an asynchronous function runs: nonisolated and @concurrent
An async function that doesn't belong to any actor: where does it run? The answer changed in Swift
6.2 and depends on a setting, so it's worth knowing it exactly:
Without settings, a nonisolated async function always leaves its caller's actor and runs on the
global thread pool. That's what happens in this part's Linux programs.
With the NonisolatedNonsendingByDefault feature turned on, the same function runs on its caller's
actor (as if it were declared nonisolated(nonsending)). That's what happens in the SwiftUI
packages and in the app.
To ask explicitly for "run off my caller's actor," in either case, you mark the function
@concurrent. That's the way to move heavy work off the main actor:
p2-concurrencia (Swift 6, no default isolation) · Concurrent.swift
// @concurrent: always runs on the global pool, never on the caller's actor.@concurrentfunc checksum(of values: [Int]) async -> Int { values.reduce(0) { $0 + $1 * $1 } // stands for heavy work}@MainActorfinal class ReportScreen { private(set) var text = "" func update() async { let sum = await checksum(of: Array(1...1_000)) // off the main actor text = "checksum: \(sum)" // back on it }}let screen = ReportScreen()await screen.update()print(screen.text)
checksum: 333833500
update() is on the main actor; checksum runs off it (on the global pool) even though the main
actor calls it, and the result comes back to the main actor to write text. The sum of squares
stands for any computation you don't want to do on the thread that draws.
Whether a computation blocks the main actor in a real app isn't something you guess: you measure it
with Instruments, Xcode's profiling tool, with its Time Profiler and Hangs templates.
Part 3 uses them.
The settings, at last
Now you can read the settings the Before You Start section left pending.
A module's default isolation (each target of a package or a project) is nonisolated, as in the Linux
programs, unless you change it: with -default-isolation MainActor on the compiler or
.defaultIsolation(MainActor.self) in a package, everything that doesn't say otherwise is inferred
@MainActor. This is p2-swiftui's Package.swift; p2-arquitectura's has the same settings:
p2-swiftui · Package.swift
// The same concurrency settings as the app: Swift 6 language mode (the default// for tools 6.x), MainActor by default, and the two parts of Approachable// Concurrency that the Swift 6 mode does not already turn on.let appSettings: [SwiftSetting] = [ .defaultIsolation(MainActor.self), .enableUpcomingFeature("NonisolatedNonsendingByDefault"), .enableUpcomingFeature("InferIsolatedConformances"),]
Approachable Concurrency, the third setting, turns on in the package the two features the Swift 6
mode doesn't bring yet; the details are in the box.
Going deeper
Approachable Concurrency is a bundle of five features:
DisableOutwardActorInference, GlobalActorIsolatedTypesUsability, InferIsolatedConformances,
InferSendableFromCaptures, and NonisolatedNonsendingByDefault. The package turns on only two
because the Swift 6 mode already includes the other three. (The language mode and the compiler
version are different things: Swift 6.4.2 compiles in modes 6, 5, 4.2, and 4.)
I checked it by asking the compiler for them by hand, in the p2-swiftui folder, with
xcrun swiftc -swift-version 6 -enable-upcoming-feature DisableOutwardActorInference -enable-upcoming-feature GlobalActorIsolatedTypesUsability -enable-upcoming-feature InferSendableFromCaptures -typecheck errores/SwiftSixFeatures.swift:
<unknown>:0: warning: upcoming feature 'InferSendableFromCaptures' already enabled as of the Swift 6 language mode<unknown>:0: warning: upcoming feature 'GlobalActorIsolatedTypesUsability' already enabled as of the Swift 6 language mode<unknown>:0: warning: upcoming feature 'DisableOutwardActorInference' already enabled as of the Swift 6 language mode
In an Xcode project, the same settings live on the target:
Select the project in the navigator on the left and choose the app target.
Open the Build Settings tab and type into the search field.
"Default Actor Isolation" (SWIFT_DEFAULT_ACTOR_ISOLATION, values nonisolated or MainActor)
and "Approachable Concurrency" (SWIFT_APPROACHABLE_CONCURRENCY) are in the Swift compiler's
concurrency group; "Swift Language Version" (SWIFT_VERSION), in the language group.
Xcode 27.2's app template comes with MainActor by default and Approachable Concurrency turned on,
but with the language mode on Swift 5 (I read it in the template's files); the part 4 app changes it
to Swift 6.
The usual mistake: copying a concurrency example between projects with different settings and
concluding that "the compiler is broken." The same nonisolated async function runs on the main
actor in a project with NonisolatedNonsendingByDefault and off it in one without the feature; code
that compiles without warnings in one can produce isolation errors in the other. Before debugging,
look at the three settings.
Each domain protects its state; crossing from one to another costs an await.
What to take away: an actor lets in one task at a time, but at each await another one can come
in; and where a function runs depends on its isolation, not on a thread.
Check what you learned. In an actor, if balance >= amount { await audit.arrive(); balance -= amount }.
What can go wrong?
Solution
during the await audit.arrive() the actor gives up the turn and another task can
withdraw money. On returning, the earlier check no longer holds and the balance can go negative. You
have to check again after the await, or subtract before suspending.
Going deeper
MainActor.assumeIsolated lets synchronous code assert "I'm on the main actor"
and use its state without await; it checks this at run time and, if it isn't true, stops the
program. It's for older APIs that call you on the main thread without saying so in their type, not
for silencing the compiler.
The concurrency example in the language guide is written with the behavior from before SE-0461:
its sentence about where downloadPhoto runs only holds without NonisolatedNonsendingByDefault.
At WWDC25, Apple recommended Approachable Concurrency for every project and the main actor by
default for the app module and the interface modules. The code inside #Preview runs explicitly on the main actor.
Sendable and Data Races
A bug that shows up once every thousand runs, only on one user's phone and never with the debugger
attached: that's what data races look like in an app. The Swift 6 mode turns them into compile
errors, and this section teaches you to read them.
Data race and race condition
A data race happens when two threads access the same memory at the same time, without
synchronization, and at least one of them writes. The result is undefined: a half-written value, a
counter that loses increments, an app crash.
A race condition is broader: a result that depends on the order in which things happen. The
double withdrawal in the previous section was a race
condition without a data race: the actor prevented simultaneous accesses, but not the wrong order.
The distinction matters because the compiler can guarantee one and not the other. With the Swift 6
mode, which is opt-in and chosen per target, the compiler guarantees the program has no data races in
the code it checks (@unchecked Sendable, nonisolated(unsafe), unsafe pointers, which access memory
without Swift's checks, and C code are left out).
Race conditions are still your job.
Two real errors
Two children of a task group increment the same variable:
Before
p2-concurrencia (Swift 6, no default isolation) · errores/DataRace.swift
func countInParallel() async { var count = 0 await withTaskGroup(of: Void.self) { group in group.addTask { count += 1 } // two children write the same variable group.addTask { count += 1 } } print(count)}
After
errores/DataRace.swift:5:15: error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace] 3 | var count = 0 4 | await withTaskGroup(of: Void.self) { group in 5 | group.addTask { count += 1 } // two children write the same variable | | `- note: closure captures reference to mutable var 'count' which remains modifiable by code in the current isolation context | `- error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace] 6 | group.addTask { count += 1 } 7 | }errores/DataRace.swift:6:15: error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace] 4 | await withTaskGroup(of: Void.self) { group in 5 | group.addTask { count += 1 } // two children write the same variable 6 | group.addTask { count += 1 } | | `- note: closure captures reference to mutable var 'count' which remains modifiable by code in the current isolation context | `- error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace] 7 | } 8 | print(count)[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>[#SendingClosureRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-closure-risks-data-race>
(These errors are produced by region analysis, which only runs in a full build: with
swiftc -typecheck they don't show up.) The compiler doesn't say "data race": it says that sending
the closure to the child task "risks causing data races," because it captures a reference to
count, a variable that code outside can also modify.
With two children, that's two possible writes at the same time. The fix isn't to silence the error:
it's for each child to return its share (group.addTask { 1 }) and for the parent scope to add up
the results in the for await, as the group in the tasks section did.
Try it yourself: in p2-concurrencia, swift -swift-version 6 errores/DataRace.swift doesn't
run anything: the compiler stops with these two errors. That's normal in Swift 6, and it's exactly
what you want: the failure arrives before the program exists.
The second error: a draft (a non-final class with a mutable property) is sent to an actor and is
still used outside.
Before
p2-concurrencia (Swift 6, no default isolation) · errores/NonSendable.swift
class Draft { // not final, mutable: not Sendable var title = ""}actor Outbox { private var drafts: [Draft] = [] func add(_ draft: Draft) { drafts.append(draft) }}func save(_ draft: Draft, to outbox: Outbox) async { await outbox.add(draft) // the draft crosses into the actor... draft.title = "Edited" // ...and is still used out here}
After
errores/NonSendable.swift:15:18: error: sending 'draft' risks causing data races [#RegionIsolation::SendingRisksDataRace]13 |14 | func save(_ draft: Draft, to outbox: Outbox) async {15 | await outbox.add(draft) // the draft crosses into the actor... | |- error: sending 'draft' risks causing data races [#RegionIsolation::SendingRisksDataRace] | `- note: sending 'draft' to actor-isolated instance method 'add' risks causing data races between actor-isolated code and code in the current isolation context16 | draft.title = "Edited" // ...and is still used out here17 | }[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
After the await outbox.add(draft), the actor has a reference to the draft and so does the outside
function: both could write title at the same time. The compiler catches it at the point of sending.
Sendable: what can cross
An isolation domain is each zone of the program with its own protection: an actor, the main
actor, or nonisolated code. Sendable is the protocol that marks the types whose values can be
shared between isolation domains (between actors, between tasks) with no risk of a data race. It has
no methods: it's a promise the compiler checks. Its rules:
A non-public struct or enum whose properties are all Sendable is Sendable without you writing
anything: the compiler infers it. The basic types (Int, String, Bool, arrays of Sendable)
are.
A class can only be Sendable if it's final, has no superclass (or inherits from NSObject),
and its stored properties are constants (let) of Sendable types.
A class isolated to the main actor is Sendable as is: the actor coordinates every access to its
state.
Actors are Sendable: their state is already protected.
(Sendable has been implemented since Swift 5.7, according to the status of its proposal, SE-0302.)
There are four fixes for the draft, from most to least preferable depending on the case: make it a
struct (each side has its own copy), make it a final class with let properties, isolate it to the
main actor if it's interface state, or turn the owner into an actor.
Regions: sending something nobody uses anymore
Not every value that crosses a domain has to be Sendable. Since Swift 6, the compiler tracks
regions of values: if a non-Sendable value is created, sent to another domain, and never used
again from the original one, the send is safe, because no one else can touch it.
p2-concurrencia (Swift 6, no default isolation) · RegionSending.swift
class Draft { // still not Sendable var title = ""}actor Outbox { private var drafts: [Draft] = [] func add(_ draft: Draft) { drafts.append(draft) } var count: Int { drafts.count }}func save(to outbox: Outbox) async { let draft = Draft() // a fresh value: no one else can see it draft.title = "Weekly report" await outbox.add(draft) // sent, and never touched again out here print("drafts in the outbox:", await outbox.count)}await save(to: Outbox())
drafts in the outbox: 1
Draft still isn't Sendable, and it compiles anyway: the draft is created inside save, no one
else has a reference, and after sending it the function never touches it again. If you added
draft.title = "Edited" after the await, you'd be back to the previous section's error. When a
function needs to demand that in its signature, it marks the parameter with sending: the value has
to arrive disconnected from everything else.
The counter from the state section, explained
In the state section I used a ChangeCounter without showing it, because withObservationTracking
calls its change closure from the thread that modifies the model, and that closure has to be able to
cross domains. Now you can read it:
p2-swiftui · Support/ChangeCounter.swift
nonisolated final class ChangeCounter: Sendable { private let count = Mutex(0) func increment() { count.withLock { $0 += 1 } } var value: Int { count.withLock { $0 } }}
It's a final, Sendable class whose only state is a constant: a Mutex (from the Synchronization
library, macOS 15 and iOS 18) that protects the integer and only lets you touch it inside
withLock. It's marked nonisolated because the package uses the main actor by default and this
type must not belong to any actor.
The usual mistake: writing @unchecked Sendable to make the error go away. That annotation
tells the compiler "trust me, I synchronize," and turns off the check for that type. It's
legitimate only when there really is a synchronization mechanism the compiler can't see (a lock in
an older type, for example). Without that lock, the error becomes a data race again, now invisible.
What to take away: a Sendable error says which value crosses domains and from where; you fix
it by copying, isolating, or returning the value, never by silencing the compiler.
Check what you learned. Does an actor eliminate race conditions?
Solution
no. It eliminates data races on its state, because only one task at a time touches
it; but it's reentrant, and between two awaits the order of operations can still produce a wrong
result. The double withdrawal showed it.
Going deeper
the Thread Sanitizer (the Xcode tool that detects data races at run time) is a
topic for part 3; it's for code the compiler can't check, like code that uses
@unchecked Sendable or C APIs.
As for why the part 4 app uses the main actor by default: almost
all of its code is interface and interface state, so the default isolation saves annotations and
this section's errors show up less. The cost is that heavy work has to be moved off the main actor
on purpose, with @concurrent.
Note: a good point for a break. You're about 105 of the 150 minutes in, and concurrency is
complete; what's left is putting all the pieces
together into an architecture and practicing for the interview.
Architecture: MVC, MVVM, and Clean Without Overengineering
You now have views, state, an HTTP client, and safe concurrency. If you put them all in the same
view, it works; the problem arrives with the first test you want to write and with the first API
change. Architecture, here, means one thing: deciding which part of the code knows about what.
From MVC to MVVM
MVC (model, view, controller) is the pattern UIKit apps were born with: the model has the data,
the view draws it, and the controller (UIViewController) connects them. In practice, the controller
ended up with everything that was neither model nor view (networking, validation, navigation), and
the community gave the symptom a name: the Massive View Controller.
MVVM (model, view, view model) splits that mix differently. The view only draws and forwards
what the user does. The view model is an object that holds the screen's state and the actions
that change it, without knowing anything about SwiftUI: "loading," "list with two tasks," "failed."
In SwiftUI it fits naturally: the view model is an @Observable class, the view reads its state, and
the state section already gave you the ownership rules.
The layers and which way they point
Clean Architecture adds a rule: dependencies point inward. At the center is the domain, the
types and rules of the problem (a task, "a task without a title can't be completed"), which knows
nothing about the network, the database, or the interface.
Around it, the presentation (view and view model) and the data (the HTTP client, the local database).
The presentation uses the domain; the data implements it. MVVM and Clean don't compete: MVVM
organizes the presentation layer, Clean organizes the dependencies between layers.
Before the code, what this example simplifies on purpose: the error message is fixed (and
downloadTodos turns any code other than 200 into a URLError, so a 404 looks like a network
failure), the repository decodes on the main actor, and its save does nothing. And one known
limitation: every reload sets the state to .loading, so a list that's already loaded is swapped for
the spinner for a moment. At the end of the section I say what each case
would need. The task list's domain:
p2-arquitectura · Domain.swift
// Domain: plain types and rules. No SwiftUI, no networking, no database.struct TaskItem: Identifiable, Equatable { let id: Int var title: String var isDone = false // A rule of the domain, so every screen and every data source obeys it. var canBeCompleted: Bool { !title.trimmingCharacters(in: .whitespaces).isEmpty }}// What the presentation layer needs from "somewhere that stores tasks".protocol TaskRepository { func fetchAll() async throws -> [TaskItem] func save(_ task: TaskItem) async throws}
This TaskItem is a different type from the one in the lists section: it carries the server's
integer id instead of a UUID, because this package talks to the API. TaskRepository is a
repository: a protocol that says what the presentation needs from "something that stores tasks"
(read them all, save one) without saying where they live. The canBeCompleted rule is in the domain,
not in the view or in the repository: that way every screen and every data source obeys it.
The view model, with its dependency injected
p2-arquitectura · TaskListViewModel.swift
enum LoadState: Equatable { case idle case loading case loaded([TaskItem]) case failed(String)}@Observablefinal class TaskListViewModel { // MainActor by default in this module private(set) var state: LoadState = .idle private let repository: any TaskRepository init(repository: any TaskRepository) { // dependency injection by initializer self.repository = repository } func load() async { state = .loading do { let tasks = try await repository.fetchAll() guard !Task.isCancelled else { return } // a cancelled load never writes state = .loaded(tasks) } catch { guard !Task.isCancelled, !isCancellation(error) else { return } state = .failed("Couldn't load your tasks.") } }}// The two forms a cancellation takes (see the cancellation section).func isCancellation(_ error: any Error) -> Bool { error is CancellationError || (error as? URLError)?.code == .cancelled}
The core is in the init: the view model receives its repository instead of creating it. That's
dependency injection: the objects a piece needs are given to it by whoever builds it, instead of
the piece looking them up itself (in a singleton, the single global instance of a class, or in a
global variable).
The most explicit form is by initializer, as here: the dependency shows up in the signature, and you
can't create a view model without it. The type being any TaskRepository (a value of any type that
conforms to the protocol, as you saw in part 1) is what lets you
pass it the real repository or a fake one.
LoadState is the enum of the screen's states. An enum, and not three loose properties
(isLoading, tasks, errorMessage), because that way the impossible combination "loading and
failed at the same time" doesn't exist. The package is compiled with the main actor by default, so
the view model is on the main actor without writing it: its state is read and written where the
interface is drawn.
The view and the composition root
p2-arquitectura · TaskListScreen.swift
struct TaskListScreen: View { let model: TaskListViewModel // created and kept by the owner, in @State var body: some View { content .task { await model.load() } // runs when the view appears } @ViewBuilder private var content: some View { switch model.state { case .idle, .loading: ProgressView() case .loaded(let tasks): List(tasks) { task in Text(task.title) } case .failed(let message): Text(message) } }}// The composition root: the only place that picks the concrete repository.struct AppRoot: View { @State private var model = TaskListViewModel( repository: RemoteTaskRepository(download: downloadTodos) ) var body: some View { TaskListScreen(model: model) }}
TaskListScreen doesn't know where the tasks come from: it reads model.state and draws each case.
The @ViewBuilder attribute lets a property return a different view in each branch of the switch.
The .task modifier appears here for the first time: it launches an asynchronous task before the
view appears and, according to its documentation, SwiftUI cancels it "at some point after" the view
disappears, if it hasn't finished yet.
To you it behaves almost like structured concurrency, tied to the view's lifetime, because you don't
have to keep or cancel it by hand. But it isn't: SwiftUI creates an unstructured task and cancels it
later, so an old task can still be in flight when the next one starts.
That's why load() handles cancellation separately: a cancelled load writes nothing (neither the
result nor an error), and the isCancellation function recognizes the two forms a cancellation
arrives in, as in the cancellation section. AppRoot is the composition root: the only place that picks the concrete repository
(RemoteTaskRepository) and keeps the view model in @State, as its owner.
The data layer translates the server's JSON into the domain:
p2-arquitectura · RemoteTaskRepository.swift
// Data layer: knows the API's JSON shape and maps it to the domain.struct RemoteTodo: Decodable { // DTO: the shape of the server's JSON let userId: Int let id: Int let title: String let completed: Bool}struct RemoteTaskRepository: TaskRepository { let download: () async throws -> Data // the HTTP client, injected (URLSession in the app) func fetchAll() async throws -> [TaskItem] { let todos = try JSONDecoder().decode([RemoteTodo].self, from: try await download()) return todos.map { TaskItem(id: $0.id, title: $0.title, isDone: $0.completed) } } func save(_ task: TaskItem) async throws { // JSONPlaceholder only simulates writes; the app of part 4 saves locally. }}// The real download, used by AppRoot. The tests inject fixed data instead.func downloadTodos() async throws -> Data { let url = URL(string: "https://jsonplaceholder.typicode.com/todos")! let (data, response) = try await URLSession.shared.data(from: url) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) } return data}
RemoteTodo is a DTO (data transfer object): a type with the exact shape of the server's JSON,
and nothing else. TaskItem is the domain type, and the map is the
only line that knows both. download is the network dependency, also injected: in the app it's a
function that uses URLSession; in the test, a closure that returns fixed JSON.
Testing without a screen
The payoff of everything above is this: the view model is tested without a view, without a network,
and without a simulator, with a fake repository.
p2-arquitectura · FakeTaskRepository.swift
// A test double: answers what the test says and writes down what it was asked.final class FakeTaskRepository: TaskRepository { var result: Result<[TaskItem], any Error> var onFetch: () -> Void = {} // lets a test look at the state mid-load var saveFails = false // makes save throw, to test the failure path private(set) var saved: [TaskItem] = [] init(result: Result<[TaskItem], any Error>) { self.result = result } func fetchAll() async throws -> [TaskItem] { onFetch() return try result.get() } func save(_ task: TaskItem) async throws { if saveFails { throw Offline() } saved.append(task) }}struct Offline: Error {} // the error the fake throws
The fake answers whatever the test tells it and writes down what it was asked. onFetch lets the
test look at the view model's state in the middle of the load, and saveFails makes saves fail
(it's used by exercise 15).
With it, the package's tests assert: before loading,
the state is .idle; while the repository is being read it's .loading; with two tasks it ends in
.loaded with those two; with a repository that throws, it ends in
.failed("Couldn't load your tasks."); the remote repository turns {"id": 4, …, "completed": true}
into TaskItem(id: 4, title: "et porro tempora", isDone: true); and a task with a blank title can't
be completed.
Why the cancellation handling matters: the view appears, disappears (SwiftUI cancels its .task),
and appears again, and there are two loads in flight. If the second finishes first and the first
reports its cancellation afterward, a catch that turns everything into .failed would overwrite
the good list with "Couldn't load your tasks."
A test in the package reproduces exactly that sequence
with a repository whose responses the test releases by hand, and asserts that the final state is
.loaded with the two tasks; another asserts the same when the cancelled load finishes successfully
late.
The three simplifications I announced, and what they would need. The error message is fixed: a real
app would tell "no connection" apart from "the server failed" using APIError's cases, and for that
downloadTodos would have to report the status code instead of disguising it as a URLError. The remote
repository decodes the JSON on the main actor, because the package uses it by default: for 200 tasks
you won't notice, but a large volume would be moved off the main actor with a @concurrent
function.
And its save does nothing and doesn't throw, because JSONPlaceholder only simulates
writes; a real repository would throw if the server didn't save. The part 4 app solves all three. The
flicker goes away if you keep the list while reloading, for example with a separate indicator instead
of a .loading state that replaces it.
The presentation uses the domain and the data implements it: dependencies point inward.
When it's overkill
Every layer has a cost: one more file, one more name, one more jump when reading the code. The
criterion I use: an abstraction pays for itself with a test that needs it or with a second use.
The TaskRepository protocol pays for itself: without it there'd be no test without the network.
What doesn't pay for itself:
A one-line "use case" that only calls the repository (a LoadTasksUseCase that does
repository.fetchAll()): it adds no logic and no test that didn't already exist.
A protocol for every class, with a single implementation and no test that substitutes it.
Layers out of habit on a settings screen that reads and writes two Booleans.
SOLID is five object-oriented design principles gathered by Robert C. Martin; this section uses two:
single responsibility (each type has one reason to change: the view for design, the repository for
the API) and dependency inversion (the presentation depends on a domain protocol, not on the concrete
networking class). The other three show up in the same code: open/closed, because a new implementation
of the protocol is added without touching the view model; Liskov substitution, because any
implementation (the real one or the test fake) must keep what the protocol promises; and interface
segregation, because the repository protocol is small and exposes only what the screen uses.
If you come from React
A view model resembles a custom hook that groups a screen's state and logic. It's an analogy of
purpose: in SwiftUI, the view model is a reference object with identity, created once and living as
long as its owner, not a function that runs again on every update.
The usual mistake: having the view model import SwiftUI and receive views, colors, or text
already formatted for a specific cell. Then it can no longer be tested without an interface, and
every design change touches the logic. The view model exposes data and actions; the view decides
how they look.
Try it yourself: unzip p2-arquitectura.zip and run swift test in its folder: 14 tests pass,
among them the two about loads in flight (CancellationOfLoadsTests). To see how the naive code
would fail, delete the guard line in load()'s catch and run again: the test
aCancelledStaleLoadDoesNotOverwriteAGoodResult fails.
What to take away: the view draws, the view model decides, and the repository fetches the
data; every abstraction pays for itself with a test or with a second use.
Check what you learned. Where would you put the rule "a task without a title can't be
completed"?
Solution
in the domain, as TaskItem's canBeCompleted: that way every screen and every
data source obeys it. In the view, only one screen would obey it; in the repository, it would
depend on where things are stored.
Going deeper
injection can also go through SwiftUI's environment (.environment(repository)
above and @Environment below).
It's convenient for dependencies half the tree uses, but it makes
implicit what the initializer makes explicit: a view reading from the environment a repository
nobody put there isn't something the compiler can check. That's why the view model, which is what
gets tested, receives everything through its initializer, and the environment is left for the root
view if needed.
Interview Questions
Twelve questions with the level usually expected of each answer. Answer out loud before opening the
solution: in an interview there's no collapsible box. The numbering follows the series' numbering
(the first 11 are in part 1).
Question 12. (Junior) What is body, when is it recomputed, and why does the order of modifiers
matter?
Solution
body is the view's description for the current state. SwiftUI asks for it again
when some data the body read changes, compares it with the previous one, and applies the
difference. Each modifier wraps the view it receives and returns another one, so the order changes
the result: .padding().background(.yellow) paints the padding; the other way around, it doesn't.
See How SwiftUI Thinks and Composition.
Question 13. (Junior/Mid) @State, @Binding, or @Environment: how do you choose?
Solution
by the data's owner. If this view creates and owns it, @State. If a parent owns it
and lends it for editing, @Binding. If many distant views share it, the environment with
@Environment. For a reference model, @Observable kept in its owner's @State. See
State.
Question 14. (Mid) What changes when you move from ObservableObject to @Observable?
Solution
tracking becomes per property: a view updates only if something its body read
changes, whereas with ObservableObject any @Published notifies everyone. @Published and
@StateObject go away: the owner uses @State, the children receive a plain property or
@Bindable.
@EnvironmentObject becomes @Environment(Type.self). The old property wrappers require
ObservableObject and don't compile with a type that only uses Observation, so you migrate model
by model: when you convert one, you also change the property wrappers that use it.
Question 15. (Junior) Safe versus idempotent: which requests would you retry automatically?
Solution
the safe ones are GET, HEAD, OPTIONS, and TRACE; the idempotent ones, those plus PUT
and DELETE. Only those are retried on their own, on transient failures (timeout, 429, 503). POST
and PATCH aren't. Idempotent refers to the effect on the server, not to getting the same response.
See HTTP and REST.
Question 16. (Junior/Mid) 401 and 403: what does the app do in each case?
Solution
401 says valid credentials are missing: the app renews the session once and repeats;
if it fails again, it asks the user to sign in. 403 says the server understood and refuses:
repeating with the same credentials doesn't help, and the app explains that there's no permission.
RFC 6750 associates invalid_token with 401 and insufficient_scope with 403.
Question 17. (Mid) You need an upload to finish in two minutes at most, and also to stop if the
server stops sending data for 20 seconds. What do you set?
Solution
two different things. timeoutIntervalForResource = 120 on the session's
configuration sets the total limit; timeoutInterval = 20 on the request (or
timeoutIntervalForRequest on the configuration) measures inactivity. With only the second one, a
slow but steady transfer wouldn't be cut off at two minutes: only at the default total limit, 7 days.
See Robust Networking.
Question 18. (Mid) An ISO 8601 date doesn't decode, and a 404 breaks your decode. Why?
Solution
because of the default date strategy (see the dates
section): you have to set .iso8601. And the 404 arrives with a body that isn't a task (in JSONPlaceholder,
{}): the client has to look at the status code before decoding, so it reports "doesn't exist"
and not "invalid JSON."
Question 19. (Mid) What does await guarantee?
Solution
that this point can suspend the function without blocking the thread. It doesn't
guarantee the function continues on the same thread. What is guaranteed is isolation: if the
function is on an actor, on returning it continues on that actor. See async and await.
Question 20. (Mid) async let, task group, Task {}, and Task.detached: how do they differ,
and how is each one cancelled?
Solution
async let and groups create child tasks, tied to the scope: they don't outlive it
and they're cancelled with their parent. Task {} creates an unstructured task that inherits
isolation, priority, and task-local values; Task.detached, one that inherits nothing. Unstructured
tasks are cancelled with cancel() on their reference. In every case cancellation is cooperative:
the code checks it with Task.checkCancellation() or Task.isCancelled.
Question 21. (Mid/Senior) Is @MainActor the same as the main thread? What does
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor do?
Solution
they aren't the same: code is isolated to the main actor, an actor whose executor is
equivalent to the main queue, and the execution environment runs it on the main thread; the compiler reasons
about the actor. The setting makes everything in that module that doesn't say otherwise be inferred
@MainActor. The language default is still nonisolated: it's a per-module setting. See
Actors and the Main Actor.
Question 22. (Senior) Your Outbox actor protects its array of drafts, and still the compiler
rejects await outbox.add(draft) when Draft is a class. Why, if the actor is already safe, and what
do you do?
Solution
the actor protects its state, but the reference to the draft stays on both sides: the
actor and the caller could write title at the same time. Sendable marks the types that can cross
domains without that risk, and the Swift 6 mode checks it.
Fixes: make Draft a struct, a final
class with let properties, isolate it on the main actor, or don't use the value again after
sending it (regions). And separately: the actor doesn't prevent race conditions between two
awaits either. See Sendable and Data Races.
Question 23. (Mid/Senior) How do MVVM and Clean Architecture coexist, and when are layers too
many?
Solution
MVVM organizes the presentation (a view without logic and a view model with state and
actions); Clean organizes the dependencies, which point toward a domain that knows nothing about
the network or the database. A layer is too much if it brings neither a test that needs it nor a
second use: a use case that only forwards to the repository, or a protocol with a single
implementation and no test. See Architecture.
Note: a good point for a break before the exercises. You're about 125 of the 150 minutes in, and
each exercise asks you to write code: it's better to do it with a fresh mind.
Interview Exercises
Eight coding exercises, 8 through 15 in the series' numbering. Each one states its level and where
it's done; try to solve it before opening the solution, which brings the verified code, the real
output, the frequent mistakes, how it's evaluated, and a follow-up question.
Exercise 8. Count the completed tasks (Junior). Decode these three real JSONPlaceholder tasks
(numbers 1, 2, and 4) and print how many there are and how many are completed:
Requirements: a struct with the API's four properties; JSONDecoder; the output
total: 3, completed: 1.
Constraints: synthesized Codable, no manual decoding. Write everything in a file Ex08.swift
(the JSON goes inside, as text) and run it with swift Ex08.swift, on macOS or Linux.
Solutionp2-entrevista · Ex08CountCompleted.swift
import Foundation// Three real todos from https://jsonplaceholder.typicode.com/todos (ids 1, 2 and 4).let fixture = Data("""[ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }, { "userId": 1, "id": 2, "title": "quis ut nam facilis et officia qui", "completed": false }, { "userId": 1, "id": 4, "title": "et porro tempora", "completed": true }]""".utf8)struct Todo: Decodable { let userId: Int let id: Int let title: String let completed: Bool}func summary(of data: Data) throws -> String { let todos = try JSONDecoder().decode([Todo].self, from: data) let completed = todos.filter(\.completed).count return "total: \(todos.count), completed: \(completed)"}do { print(try summary(of: fixture))} catch { print("could not decode:", error)}
Explanation.Todo declares Decodable and the compiler synthesizes the decoding, because its
four properties are of decodable types with the same names as the keys. [Todo].self decodes the
whole array, and filter(\.completed) uses a key path as a function to keep the completed ones.
The do/catch reports whether the JSON doesn't have the expected shape.
Expected result:
total: 3, completed: 1
Common mistakes. Calling the title property todo (that's its name in DummyJSON, another
test API; in JSONPlaceholder it's title), and decoding a single Todo when the JSON is an array.
Evaluation criteria. A minimal model without unnecessary optionals; try inside a
do/catch; no ! to silence errors.
Follow-up question. What if completed arrives as null? Decoding fails (with which case, you
measured in the URLSession and Codable section). If the server can send null,
the property is declared Bool? and the app decides what it means.
Exercise 9. snake_case keys and ISO 8601 dates (Mid). Decode a JSON with the keys due_date and
is_done (the date in ISO 8601) into a struct with Swift names, and report each error with its case.
Requirements: properties dueDate: Date and isDone: Bool; a function that returns
ok: <seconds> <isDone> or the error case (with its key when the error carries one).
Constraints: no CodingKeys; the output can't use debugDescription or localizedDescription
(they change between platforms).
Solutionp2-entrevista · Ex09DatesAndKeys.swift
struct Assignment: Decodable { let title: String let dueDate: Date // arrives as "due_date" let isDone: Bool // arrives as "is_done"}func makeDecoder() -> JSONDecoder { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase decoder.dateDecodingStrategy = .iso8601 return decoder}func report(_ json: String) -> String { do { let a = try makeDecoder().decode(Assignment.self, from: Data(json.utf8)) return "ok: \(Int(a.dueDate.timeIntervalSince1970)) \(a.isDone)" } catch DecodingError.keyNotFound(let key, _) { return "keyNotFound: \(key.stringValue)" } catch DecodingError.typeMismatch(_, let context) { return "typeMismatch: \(context.codingPath.map(\.stringValue).joined(separator: "."))" } catch DecodingError.dataCorrupted { return "dataCorrupted" } catch { return "other error" }}print(report(#"{"title": "Essay", "due_date": "2026-11-20T10:00:00Z", "is_done": false}"#))print(report(#"{"due_date": "2026-11-20T10:00:00Z", "is_done": false}"#))print(report(#"{"title": "Essay", "due_date": "20/11/2026", "is_done": false}"#))
Explanation.convertFromSnakeCase translates due_date to dueDate and is_done to isDone
for the whole decoder, and .iso8601 reads the date as text. Each catch catches one
DecodingError case with a pattern, and the last one catches any other error so the function
doesn't throw.
Common mistakes. Leaving the default date strategy (it fails with typeMismatch), and
combining convertFromSnakeCase with CodingKeys written in snake_case: the strategy is applied
first and the keys no longer match.
Evaluation criteria. Correct strategies in a single reusable decoder; errors that are useful to
whoever debugs, with case and key.
Follow-up question.CodingKeys or a strategy? A strategy if the whole API is consistent;
CodingKeys if only a few keys differ or if you want each key's name written in the type.
Exercise 10. One task by id, with separate errors (Mid). Add to TodosClient a function
todo(id:) that requests /todos/{id} and returns a Todo, with the same error separation as
todos(), and check it without the network.
For the check, I give you the fake network protocol from the
URLSession section ready-made:
// A fake network. Each test gets its own host, so tests can run in parallel.final class StubURLProtocol: URLProtocol { enum Reply: Sendable { case http(status: Int, headers: [String: String] = [:], body: Data = Data()) case failure(URLError.Code) case hang // never answers; only cancelling ends the request } private static let replies = Mutex<[String: [Reply]]>([:]) private static let received = Mutex<[String: [URLRequest]]>([:]) // A session whose requests to the returned host get `replies`, in order. static func session(replying replies: [Reply]) -> (session: URLSession, baseURL: URL) { let host = "test-\(UUID().uuidString.lowercased()).example" self.replies.withLock { $0[host] = replies } let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [StubURLProtocol.self] // the only protocol it may use return (URLSession(configuration: configuration), URL(string: "https://\(host)")!) } static func requests(to url: URL) -> [URLRequest] { received.withLock { $0[url.host() ?? ""] ?? [] } } override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } override func startLoading() { let host = request.url?.host() ?? "" Self.received.withLock { $0[host, default: []].append(request) } let reply = Self.replies.withLock { all -> Reply in guard var queue = all[host], !queue.isEmpty else { return .failure(.cannotFindHost) } let next = queue.removeFirst() all[host] = queue return next } switch reply { case .http(let status, let headers, let body): let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)! client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) client?.urlProtocol(self, didLoad: body) client?.urlProtocolDidFinishLoading(self) case .failure(let code): client?.urlProtocol(self, didFailWithError: URLError(code)) case .hang: break } } override func stopLoading() {}}
StubURLProtocol.session(replying:) returns a session and a base URL whose requests get the replies
in the list, in order. Each call uses its own host (test-<uuid>.example), and the Mutex protects
the dictionaries because the session calls the protocol from its own threads.
Requirements: an injected URLSession; 200 returns the Todo; 404 throws APIError.status(404);
an expired timeout throws APIError.transport. With a session that answers 200, 404, and an
expired timeout, three calls (ids 1, 9999, and 2) print one line per case.
Constraints: no network; no URLSession.shared inside the client.
How to do it: in p2-red.zip, the file Sources/TodosAPI/TodoByID.swift contains the solution;
empty it and write your own. Then, in the package's folder, run
swift test --filter Exercise10Check: it runs the check below with your code and compares it with
the three expected lines. You don't have to create the package or write the test.
Solutionp2-red · TodoByID.swift
extension TodosClient { func todo(id: Int) async throws -> Todo { var request = URLRequest(url: baseURL.appending(path: "todos/\(id)")) request.setValue("application/json", forHTTPHeaderField: "Accept") let (data, http) = try await send(request) guard (200..<300).contains(http.statusCode) else { throw APIError.status(http.statusCode) // a 404 from JSONPlaceholder carries "{}" } do { return try JSONDecoder().decode(Todo.self, from: data) } catch let error as DecodingError { throw APIError.decoding(error) } } // Transport only: turns "no answer" into APIError.transport. private func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { do { let (data, response) = try await session.data(for: request) guard let http = response as? HTTPURLResponse else { throw APIError.transport(URLError(.badServerResponse)) } return (data, http) } catch let error as URLError { throw APIError.transport(error) } }}
Explanation.send concentrates the transport: it turns a URLError into .transport and the
response into an HTTPURLResponse. todo(id:) decides on the status and decodes only a 2xx.
Throwing APIError.transport inside the do doesn't wrap it again, because the catch only
catches URLError. The check builds the fake session and calls three times:
Common mistakes. Decoding before looking at the status; creating the session inside the
client (it can't be checked without the network); a fake protocol with a single shared static
variable, which gets overwritten when two checks run at the same time.
Evaluation criteria. Injection of the session; the three error cases kept separate; a
deterministic check that doesn't touch the network.
Follow-up question. How would you add retries only for the GET? With the RetryPolicy from the
Robust Networking section inside send: todo(id:) is a GET, and the policy
already rejects non-idempotent methods.
Exercise 11. A model created in the wrong place (Junior/Mid). This screen creates its
@Observable model inside body and passes it to the child with @ObservedObject. Fix it without
changing what it does.
Do it in Xcode. Create an app project (File › New › Project › iOS › App). Add a file with File › New ›
File from Template › SwiftUI View, name it DraftScreen.swift, and replace its contents with the code
below, which includes the model and a #Preview block. Open the canvas with Editor › Canvas: while
the file doesn't compile, the canvas shows the error instead of the view; once you fix it, the screen
appears and you can type into the field.
p2-swiftui · errores/BrokenDraftScreen.swift
import Observationimport SwiftUI@Observablefinal class DraftModel { var title = "" var canSave: Bool { !title.trimmingCharacters(in: .whitespaces).isEmpty }}struct DraftScreen: View { var body: some View { let model = DraftModel() // a new model on every body DraftForm(model: model) }}struct DraftForm: View { @ObservedObject var model: DraftModel var body: some View { TextField("Title", text: $model.title) Button("Save") {} .disabled(!model.canSave) }}#Preview { DraftScreen()}
The compiler answers:
errores/BrokenDraftScreen.swift:19:6: error: generic struct 'ObservedObject' requires that 'DraftModel' conform to 'ObservableObject'17 |18 | struct DraftForm: View {19 | @ObservedObject var model: DraftModel | `- error: generic struct 'ObservedObject' requires that 'DraftModel' conform to 'ObservableObject'20 |21 | var body: some View {SwiftUI.ObservedObject:2:67: note: where 'ObjectType' = 'DraftModel' 1 | @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) 2 | @MainActor @propertyWrapper @preconcurrency @frozen public struct ObservedObject<ObjectType> : DynamicProperty where ObjectType : ObservableObject { | `- note: where 'ObjectType' = 'DraftModel' 3 | @MainActor @dynamicMemberLookup @preconcurrency @frozen public struct Wrapper { 4 | @MainActor @preconcurrency public subscript<Subject>(dynamicMember keyPath: ReferenceWritableKeyPath<ObjectType, Subject>) -> Binding<Subject> { get }
Requirements: the Save button is enabled when the title has text; what was typed isn't lost when
the screen updates.
Constraints: no ObservableObject; the model is still @Observable.
Solutionp2-swiftui · Exercise11.swift
@Observablefinal class DraftModel { var title = "" var canSave: Bool { !title.trimmingCharacters(in: .whitespaces).isEmpty }}struct DraftScreen: View { @State private var model = DraftModel() // created once, owned by this view var body: some View { DraftForm(model: model) }}struct DraftForm: View { @Bindable var model: DraftModel // not @ObservedObject: this is not an ObservableObject var body: some View { TextField("Title", text: $model.title) Button("Save") {} .disabled(!model.canSave) }}#Preview { DraftScreen()}
Explanation. Two bugs, one the compiler sees and one it doesn't. The one it sees:
@ObservedObject requires an ObservableObject, and DraftModel only uses Observation. The one it
doesn't see: creating the model in body recreates it on every update, and the child receives an
empty model. The owner keeps it in a @State, and the child uses @Bindable because it needs
$model.title.
Expected result. The fixed version compiles, and the package's test asserts that canSave
starts as false, becomes true when you type "Visit the bank," and goes back to false with a
title of only spaces; and that a view reading canSave gets a notification when title changes.
Common mistakes. Fixing only the compiler error by changing @ObservedObject to a plain
property and leaving the model in body; creating the model in the child's init, which gets
recreated just the same.
Evaluation criteria. The right owner; @Bindable only where a binding is needed.
Follow-up question. What happens if you change DraftScreen's identity (for example, with an
.id that changes)? SwiftUI treats it as a new view: its @State is created again and the draft is
lost, as in the identity section.
Exercise 12. A view model that writes from off the main actor (Mid). This view model updates
title from a nonisolated async function, and the compiler rejects it. Fix it.
p2-entrevista (Swift 6, no default isolation) · errores/Ex12Before.swift
final class ProfileViewModel { // not isolated to any actor var title = "Loading…" func refresh() async { // nonisolated async title = await fetchTitle() }}@MainActorfunc onAppear(_ model: ProfileViewModel) async { await model.refresh()}
errores/Ex12Before.swift:16:17: error: sending 'model' risks causing data races [#RegionIsolation::SendingRisksDataRace]14 | @MainActor15 | func onAppear(_ model: ProfileViewModel) async {16 | await model.refresh() | |- error: sending 'model' risks causing data races [#RegionIsolation::SendingRisksDataRace] | `- note: sending main actor-isolated 'model' to @concurrent instance method 'refresh()' risks causing data races between @concurrent and main actor-isolated uses17 | }[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
Requirements: the title ends up as Ready; getting the title can still happen off the main actor.
Constraints: Swift 6 mode, no @unchecked Sendable and no DispatchQueue. It's compiled with
swiftc -swift-version 6, without default isolation.
Solutionp2-entrevista (Swift 6, no default isolation) · Ex12MainActorViewModel.swift
// Heavy or slow work: allowed to leave the main actor.@concurrentfunc fetchTitle() async -> String { "Ready"}@MainActorfinal class ProfileViewModel { // its state lives on the main actor private(set) var title = "Loading…" func refresh() async { // isolated to the main actor too title = await fetchTitle() // suspends, the work runs elsewhere, then back here }}@MainActorfunc onAppear(_ model: ProfileViewModel) async { await model.refresh() print("title:", model.title)}await onAppear(ProfileViewModel())
Explanation. The view model is interface state: it goes on the main actor, and its methods with
it. The function that gets the title is marked @concurrent, so it runs off the main actor; the
await waits for it and the result comes back to the main actor to write title. The original
error said exactly that: the model was in the main actor's region and was being sent to a method
that runs elsewhere.
Expected result:
title: Ready
Common mistakes. Wrapping the write in DispatchQueue.main.async inside asynchronous code (it
mixes two concurrency models and the compiler can't check it); marking the class
@unchecked Sendable to silence the error.
Evaluation criteria. Understands what's isolated and where; a minimal fix; the slow work stays
off the main actor.
Follow-up question. What changes with the app's settings? With the main actor by default, the
class would already be on the main actor without writing it, and you'd only need to mark
@concurrent on the function that has to leave. With Approachable Concurrency
(NonisolatedNonsendingByDefault), in addition, the original code compiles: refresh() runs on its
caller's actor. But the view model would still not be isolated, and marking it @MainActor is
still the right call.
Exercise 13. Concurrency that keeps the input order (Mid). Write a generic function that applies
an asynchronous transformation to each element in parallel and returns the results in input order.
Requirements: withThrowingTaskGroup; with the input ["alpha", "b", "charlie", "d"] and a
simulated source where longer strings take longer, the output is always the input in the same
order.
Constraints: a simulated source, no network; if a transformation throws, the function throws.
Solutionp2-entrevista (Swift 6, no default isolation) · Ex13KeepInputOrder.swift
// A simulated source: longer names take more turns, so children finish// out of order. Nothing touches the network.func fetch(_ name: String) async throws -> String { for _ in 0..<(name.count * 10) { await Task.yield() } return name.uppercased()}func mapConcurrently<Input: Sendable, Output: Sendable>( _ inputs: [Input], _ transform: @escaping @Sendable (Input) async throws -> Output) async throws -> [Output] { try await withThrowingTaskGroup(of: (Int, Output).self) { group in for (index, input) in inputs.enumerated() { group.addTask { (index, try await transform(input)) } } var slots = [Output?](repeating: nil, count: inputs.count) for try await (index, output) in group { slots[index] = output } return slots.map { $0! } // every slot was filled, or the group threw }}print(try await mapConcurrently(["alpha", "b", "charlie", "d"]) { try await fetch($0) })
Explanation. The simulated source uppercases the string and takes longer with long strings, so
the children finish out of order; the output tests both the transformation and the order at once.
Each child returns (index, result) and the parent puts them in their position.
The generics
require Sendable because the inputs travel to the children and the outputs come back; the
transformation is @Sendable because several children use it at the same time. The final ! is
safe: if any child threw, the group threw before getting there.
Expected result:
["ALPHA", "B", "CHARLIE", "D"]
Common mistakes. Appending the results to an array in order of arrival and assuming it's the
input order; capturing a var array in the children to write into it (the error from the Sendable
section).
Evaluation criteria. Structured concurrency; errors that propagate; no assumed order.
Follow-up question. How would you limit it to two simultaneous transformations? By adding only
two children to the group at the start and, each time one finishes, adding the next one inside the
for try await.
Exercise 14. A cache that doesn't download twice (Senior). This ImageCache actor downloads the
same image five times when five screens request it at the same time. Fix it so there's a single
download per URL. The whole program, with the download counter and the five requests:
p2-entrevista (Swift 6, no default isolation) · Ex14BrokenCache.swift
import Foundation// Compiled in Swift 6 mode with no default isolation (Linux, swiftc).// Counts how many times the (fake) network is really used.actor LoadCounter { private(set) var loads = 0 func record() { loads += 1 }}// Holds each download until all five requests are in flight, so the// interleaving (and the output) is the same on every run.actor Rendezvous { private let expected: Int private var waiting: [CheckedContinuation<Void, Never>] = [] init(expected: Int) { self.expected = expected } func arrive() async { await withCheckedContinuation { continuation in waiting.append(continuation) if waiting.count == expected { waiting.forEach { $0.resume() } waiting.removeAll() } } }}actor ImageCache { private var stored: [URL: Data] = [:] private let load: @Sendable (URL) async throws -> Data init(load: @escaping @Sendable (URL) async throws -> Data) { self.load = load } func image(for url: URL) async throws -> Data { if let data = stored[url] { return data } // checked BEFORE the await… let data = try await load(url) // …another call can enter here stored[url] = data // …and the check above is stale return data }}let counter = LoadCounter()let gate = Rendezvous(expected: 5)let cache = ImageCache { url in await counter.record() await gate.arrive() // a slow download return Data(url.absoluteString.utf8)}let url = URL(string: "https://example.com/avatar.png")!let results = try await withThrowingTaskGroup(of: Int.self) { group in for _ in 1...5 { group.addTask { try await cache.image(for: url).count } } var sizes: [Int] = [] for try await size in group { sizes.append(size) } return sizes}print("loads: \(await counter.loads), results: \(results.count)")
swift -swift-version 6 Ex14BrokenCache.swift prints:
loads: 5, results: 5
In an app, how many downloads get repeated depends on timing; here the Rendezvous pins it down.
Requirements: with five simultaneous requests for the same URL, the download happens once and all
five receive the result.
Constraints: a single await of the loader per URL; if the download fails, the next request can
try again.
Out of scope: a memory cap. This cache grows without limit; a production one would have a cap (part
3 introduces NSCache for that) and would empty itself on a system memory warning.
Solutionp2-entrevista (Swift 6, no default isolation) · Ex14InFlightCache.swift
import Foundation// Compiled in Swift 6 mode with no default isolation (Linux, swiftc).// Counts how many times the (fake) network is really used.actor LoadCounter { private(set) var loads = 0 func record() { loads += 1 }}actor ImageCache { private var stored: [URL: Data] = [:] private var inFlight: [URL: Task<Data, Error>] = [:] private let load: @Sendable (URL) async throws -> Data init(load: @escaping @Sendable (URL) async throws -> Data) { self.load = load } func image(for url: URL) async throws -> Data { if let data = stored[url] { return data } if let running = inFlight[url] { return try await running.value } // join it let task = Task { try await load(url) } inFlight[url] = task // registered before the first await defer { inFlight[url] = nil } // also when the load fails let data = try await task.value stored[url] = data return data }}let counter = LoadCounter()let cache = ImageCache { url in await counter.record() for _ in 0..<100 { await Task.yield() } // a slow download return Data(url.absoluteString.utf8)}let url = URL(string: "https://example.com/avatar.png")!let results = try await withThrowingTaskGroup(of: Int.self) { group in for _ in 1...5 { group.addTask { try await cache.image(for: url).count } } var sizes: [Int] = [] for try await size in group { sizes.append(size) } return sizes}print("loads: \(await counter.loads), results: \(results.count)")
Explanation. The broken version checks "is it in the
cache?", does an await of the download, and writes on returning: because of reentrancy, all five
calls can pass the check before the first one writes. The fixed one registers the download in
progress (inFlight) before the first await, so the following calls find it and wait for it
instead of launching another. The defer removes it from the dictionary even if it fails, so the
next request can retry.
Task<Data, Error> is the type of a task that returns Data or throws an error, and try await task.value waits for its result: it's like the .result from the cancellation section, but instead
of giving you a Result, it throws the error. Several calls can wait on the same task's value.
Expected result:
loads: 1, results: 5
Common mistakes. Writing to the dictionary after the await; forgetting to clean up
inFlight if the download fails (every future request would wait on an old error).
Evaluation criteria. Explains reentrancy in their own words; registers before suspending;
cleans up on failure.
Follow-up question. How do you cancel the download if every screen that was waiting for it
leaves? By counting who's waiting for each URL and cancelling the inFlight task when the count
reaches zero.
Exercise 15. Moving the logic out of a view (Mid). This view loads tasks from a singleton,
toggles their state, and saves, all inside the body. Extract a view model with the repository
injected and check it without an interface, with the fake repository from the
architecture section.
p2-arquitectura · Exercise15Before.swift
struct BoardScreenBefore: View { @State private var tasks: [TaskItem] = [] @State private var error: String? var body: some View { List(tasks) { task in Button(task.title) { guard let i = tasks.firstIndex(where: { $0.id == task.id }), tasks[i].canBeCompleted else { return } tasks[i].isDone.toggle() // logic in the view TaskStore.shared.tasks = tasks // a singleton, impossible to replace } } .overlay { if let error { Text(error) } } .task { do { tasks = try await TaskStore.shared.fetch() } // the view talks to the data layer catch { self.error = "Couldn't load your tasks." } } }}
.overlay draws one view on top of another (here, the error over the list).
Requirements: loading states in an enum; toggling a task saves it to the repository; the rule
"no title, no completion" is respected; if a save fails, the list stays on screen, the task goes
back to how it was, and a message appears.
Constraints: initializer injection; no singletons.
How to do it: in p2-arquitectura.zip, the file Sources/Architecture/Exercise15.swift contains
the solution; empty it and write your TaskBoardViewModel. The package already has the settings
from the actors section. In its folder, swift test --filter exercise15Check
runs the solution's check, which prints the state after loading, after toggling task 2, and after a
save that fails on task 1.
Solutionp2-arquitectura · Exercise15.swift
@Observablefinal class TaskBoardViewModel { private(set) var state: LoadState = .idle private(set) var saveError: String? // a failed save, shown without losing the list private var saving: Set<TaskItem.ID> = [] // rows with a save in flight private let repository: any TaskRepository init(repository: any TaskRepository) { self.repository = repository } func load() async { state = .loading do { let tasks = try await repository.fetchAll() guard !Task.isCancelled else { return } state = .loaded(tasks) } catch { guard !Task.isCancelled, !isCancellation(error) else { return } state = .failed("Couldn't load your tasks.") } } func toggle(id: TaskItem.ID) async { guard case .loaded(var tasks) = state, let index = tasks.firstIndex(where: { $0.id == id }), tasks[index].canBeCompleted, !saving.contains(id) else { return } // one save per row at a time saving.insert(id) defer { saving.remove(id) } let before = tasks[index] tasks[index].isDone.toggle() state = .loaded(tasks) // optimistic: the screen updates at once saveError = nil do { try await repository.save(tasks[index]) } catch { revert(to: before) // undo only this task, keep the list saveError = "Couldn't save “\(before.title)”." } } private func revert(to task: TaskItem) { guard case .loaded(var tasks) = state, let index = tasks.firstIndex(where: { $0.id == task.id }) else { return } tasks[index] = task state = .loaded(tasks) }}struct BoardScreen: View { let model: TaskBoardViewModel var body: some View { Group { switch model.state { case .idle, .loading: ProgressView() case .loaded(let tasks): List(tasks) { task in Button(task.title) { Task { await model.toggle(id: task.id) } } } .safeAreaInset(edge: .bottom) { if let message = model.saveError { Text(message).foregroundStyle(.red) } } case .failed(let message): Text(message) } } .task { await model.load() } }}
Explanation. The view model receives any TaskRepository and exposes state, saveError, and
two actions. toggle is optimistic: it changes the state first (the screen responds to the tap
instantly) and saves afterward. If saving fails, it doesn't replace the list with an error screen:
it puts only that task back the way it was and leaves the message in saveError, which the view
shows at the bottom of the list. A failed save is a problem for one row, not for the screen.
saving blocks a second tap on the same row while its save is still in flight: without it, if the
first one failed, the rollback would also erase the second change (TaskBoardDoubleTapTests checks
it). load ignores cancellation, like the view model in the section.
The button launches a Task because its action is synchronous and toggle is asynchronous, and Group groups the branches of the switch
without drawing anything of its own, so .task is applied to them only once.
.safeAreaInset(edge: .bottom) places the message at the bottom of the list without covering it.
The check uses the fake repository from the section, with saveFails to force the error:
Task 2's save reached the repository; task 1's failed, the task went back to pending, and the list
stayed loaded. Other tests in the package assert that a failed load ends in
.failed("Couldn't load your tasks.") and that a task with a blank title is neither toggled nor
saved.
Common mistakes. A repository protocol with ten methods the screen doesn't use; empty use
cases that only forward; leaving the business rule in the button; turning a failed save into an
error for the whole screen, or leaving the optimistic change without undoing it. And one case this
solution doesn't cover: if a reload replaces the list while a save is in progress, revert(to:) can
write an old row over the new one. You avoid it by checking, before undoing, that the row is still
the one you changed.
Evaluation criteria. A fair separation (view, view model, domain, repository); the rule in the
domain; errors that aren't swallowed and don't wipe out what the user sees.
Follow-up question. Where would you put pagination? In the repository (which page to request
and how to read the Link header) and in the view model (when to request the next one); the view
only reports that the user reached the end.
What You Learned
A view is a value that describes the interface; body is recomputed when the data it read
changes, and state survives as long as the view's identity is preserved.
State has an owner: the view (@State), a parent (@Binding), the environment (@Environment),
or an @Observable model kept by its owner, which notifies only the views that read what changed;
you migrate from ObservableObject model by model, changing the property wrappers too.
A list needs unique, stable identities; a form edits a draft whose validation is a pure function;
navigation is data you can test and restore.
An HTTP client separates "there was no response," "the response was an error," and "the response
can't be understood," looks at the status before decoding, and retries only idempotent methods,
with a growing wait.
Child tasks live inside their scope, cancellation is cooperative and undoes nothing, and cancelling
a request arrives as URLError.cancelled.
An actor eliminates data races but is reentrant; the main actor isn't the same as the main thread,
even though its code runs on it, and where a function runs depends on the module's settings.
In Swift 6 mode, the compiler rejects whatever can produce a data race: a non-Sendable value that
crosses domains and keeps being used, or a closure that shares a variable. You read the error by
looking for what crosses and from where, and you fix it by copying, isolating, or returning the
value.
MVVM organizes the presentation and Clean the dependencies; each layer pays for itself with a test
or a second use.
You have twelve interview questions and eight interview exercises, solved, to review all of the
above.
What's Next
The app now knows how to load, show, and cancel. What it doesn't know yet is how to remember: if you
close the app on the subway, what you edited is lost, and the session token has no safe place.
In part 3 you choose where each
piece of data lives (UserDefaults, Keychain, SwiftData, files, and caches), you write the tests I've
only described to you in prose so far, and you diagnose fifteen real problems, from a list that
doesn't update to five 401s arriving at once.
One question before you move on: of the screens in an app you use every day, which one do you think
has a state-ownership bug, and how would you notice?
Bibliography
Official sources consulted between November 19 and 20, 2026.