Lesson 3 of 9 · 28m
Structured Concurrency with async and await
Use tasks, actors, cancellation, and MainActor boundaries deliberately so concurrent work stays ordered, cancelable, and testable.
The worst concurrency bugs do not look like concurrency bugs. They look like occasional blank screens, stale profile data, duplicate purchases, or crashes that only happen on slower phones. Swift concurrency gives you vocabulary callback code never had: ownership, cancellation, isolation, and ordering.
async means suspension, not parallel magic
An async function may suspend at await and resume later. Know which mutable state is protected and where UI-visible state may change:
func loadDashboard() async {
isLoading = true
defer { isLoading = false }
do {
dashboard = try await service.dashboard()
} catch is CancellationError {
return
} catch {
loadError = error.localizedDescription
}
}In a @MainActor view model, those property writes are serialized for the UI. That does not stop an older request from finishing after a newer one; logical races still need design.
Cancellation is part of correctness
Users navigate away, pull to refresh, sign out, and background the app. Repeated work should cancel stale work:
private var searchTask: Task<Void, Never>?
func updateSearch(query: String) {
searchTask?.cancel()
searchTask = Task {
try? await Task.sleep(for: .milliseconds(250))
guard !Task.isCancelled else { return }
await performSearch(query: query)
}
}Cooperative cancellation only works when the work checks cancellation or uses APIs that honor it. A canceled task that still writes results is a zombie: technically dead, still causing damage.
Actors protect mutable shared state
Use an actor when a service owns mutable state touched by multiple tasks:
actor TokenStore {
private var cachedToken: Token?
func token(refreshingWith refresh: @Sendable () async throws -> Token) async throws -> Token {
if let cachedToken, !cachedToken.isExpired { return cachedToken }
let fresh = try await refresh()
cachedToken = fresh
return fresh
}
}The actor serializes access. It does not design the invariant for you: two callers can still both refresh unless you store and coalesce the in-flight task.
MainActor is a boundary, not a decoration
Mark view models and UI-observable state @MainActor when their job is to drive the interface. Keep decoding and expensive transformation off it:
let index = await Task.detached(priority: .utility) {
SearchIndex.build(from: snapshot)
}.value
applyIndex(index)Do not spray @MainActor across the service layer because one property touched the wrong isolation domain. That is how networking code ends up blocking scroll performance.
Field notes
Taskinherits actor context;Task.detacheddoes not. Choose intentionally instead of copying whichever one silenced the compiler.async letcreates child work in the current scope, while unstructuredTaskcan outlive it.- Actors are reentrant across suspension points, so invariants can change between awaits.
- Test cancellation paths. Most teams test success and failure, then ship stale writes from canceled work.
Was this lesson helpful?