18 of 20 · Callbacks and concurrency
Swift 6 Concurrency
Swift concurrency replaces queues and locks with isolation. Mutable state belongs to exactly one isolation domain (the main actor, an actor, or a single task), values that cross between domains must be Sendable, and async work forms a tree of tasks that can be cancelled. In Swift 6 language mode the compiler enforces this, so data races become build errors.
How it's wired
- Every piece of mutable state belongs to one isolation domain (the main actor, an actor, or a single task).
- Crossing domains needs an await and a Sendable value, and the compiler checks it in Swift 6 language mode.
| Part | Owns | Looks like |
|---|---|---|
| @MainActor | UI state and anything touching UIKit or SwiftUI | @MainActor @Observable |
| actor | Shared mutable state off the main thread | actor ThanksRepository |
| Sendable | Values safe to share across domains | value types, immutable final classes |
| Structured tasks | Child work that's cancelled with its parent | async let, TaskGroup, .task |
| Unstructured Task | Bridge from sync code; you own cancellation | Task { }, stored handle |
Swift example: cancel stale work, survive reentrancy
Two bugs that compile fine in Swift 6, and their fixes.
Cancel the previous search
The live demo in this app is exactly this. Turn cancellation off to see the bug.
@MainActor @Observable
final class SearchModel {
private(set) var results: [Item] = []
private(set) var errorMessage: String?
private var task: Task<Void, Never>?
func queryChanged(_ text: String) {
task?.cancel() // a newer query supersedes the old one
errorMessage = nil
task = Task {
do {
let found = try await api.search(text)
guard !Task.isCancelled else { return } // superseded while awaiting
results = found
} catch is CancellationError {
// Superseded by a newer keystroke: stay quiet.
} catch {
guard !Task.isCancelled else { return }
errorMessage = "Search failed. Try again."
}
}
}
}Actor reentrancy
Two calls for the same image both miss the cache, then both download. Store the in-flight task, not just the result.
actor ImageCache {
private var cache: [URL: Task<Image, Error>] = [:]
func image(for url: URL) async throws -> Image {
if let existing = cache[url] { return try await existing.value }
let task = Task { try await download(url) }
cache[url] = task // recorded BEFORE the await, so a reentrant call reuses it
do {
return try await task.value
} catch {
cache[url] = nil // never cache a failure; the next call retries
throw error
}
}
// Note: an unstructured Task keeps downloading even if all callers cancel.
// Track waiter counts if fast-scroll cancellation matters, and bound cache size
// (LRU or NSCache + memory warning eviction) so it can't grow forever.
}What still goes wrong after it compiles
- Reentrancy. An actor runs one job at a time, but every await is a suspension point where other calls can run. Read state, await, then write it back, and you've built a race the compiler can't see. Re-check after each await or keep the critical section synchronous.
- Cancellation is cooperative. Cancelling a task only sets a flag; Task.sleep and many system APIs throw CancellationError, but your own loops and callback bridges must check Task.isCancelled or use withTaskCancellationHandler.
- Out-of-order results. Start one task per keystroke without cancelling the last, and a slow early response overwrites a fast later one. Hold the task handle, cancel it, and check for cancellation before publishing.
- Where work runs.
Task {}inherits the current actor. In Swift 6.2 (approachable concurrency), a nonisolated async function also runs on the caller's actor, and only@concurrentmoves CPU work off it. Before 6.2, nonisolated async functions hopped off automatically. - Not every lock needs an actor. For a small piece of synchronous state,
Mutex(iOS 18) orOSAllocatedUnfairLockavoids forced async and reentrancy. - Migration noise. Turn on strict checking module by module. Approachable concurrency settings (default main-actor isolation for app targets, nonisolated async functions running on the caller's actor) cut the noise a lot for UI code.
- Escape hatches. @unchecked Sendable, nonisolated(unsafe) and @preconcurrency each need a written invariant and a plan to remove them.
How I use it
| UI state | @MainActor view models and models; the default for app targets. |
|---|---|
| Shared mutable state off the main thread | An actor, with synchronous critical sections. |
| Parallel work | async let for a fixed number of calls, a task group for a dynamic number. |
| Bridging | Task {} from sync code, with a stored handle you cancel. |
Compared
GCD vs Swift concurrency
| GCD | Swift concurrency | |
|---|---|---|
| Data races | Found in testing, maybe | Compile errors in Swift 6 mode |
| Cancellation | Manual flags | Built into the task tree |
| Thread explosion | Possible with blocking work | Cooperative pool sized to cores |
| Main-thread UI | Dispatch to the main queue by hand | @MainActor, checked by the compiler |
Expert notes
- Swift 6 removes data races, not logic races. The interview follow-ups are almost always reentrancy, cancellation and where work actually runs, so have one concrete example of each.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain Swift 6 Concurrency in 30 seconds.
- Swift 6 turns data races into compile errors.
- Every piece of mutable state belongs to one isolation domain, an actor or the main actor, and only
Sendablevalues cross between domains. - What it can't catch are logic races.
- An actor is reentrant, so its state can change across any
await. - Cancellation is cooperative, so superseded work still finishes unless it checks.
- I keep UI state on the main actor, re-check invariants after every
await, and cancel work when its input changes.
Swift 6 makes data races compile errors. What concurrency bugs can you still ship?
- Logic races are still possible, because the compiler checks isolation rather than intent.
- Actor reentrancy breaks read-await-write sequences, since state can change at any suspension point.
- Missing cancellation lets superseded work finish and publish stale results.
- Heavy synchronous work can land on the main actor, because a
Task {}inherits its caller's actor, and with approachable concurrency so do nonisolated async functions. - Blocking a cooperative-pool thread on a semaphore can stall unrelated tasks.
- I'd look for all four in code review.
Search results flicker and sometimes show results for an older query. Walk through the fix.
- Each keystroke starts a search, and a slow early one finishes last.
- Keep a
Taskhandle on the main-actor model, cancel it when the query changes, and checkTask.isCancelledafter theawaitbefore assigning results. - Debounce with
Task.sleepinside the task, so cancellation also cancels the wait. - Tag results with their query if the API can't be cancelled.
You're migrating a large UIKit app to Swift 6 strict concurrency. How do you plan it?
- I'd run it as shippable steps.
- First I turn on complete concurrency checking as warnings, module by module, leaves first, and track the count per module.
- That map shows where shared mutable state really lives.
- Then UI types get
@MainActor, or default main-actor isolation in app targets, and singletons become actors or main-actor types. - Callback SDKs get wrapped once at the boundary.
@preconcurrencyand@unchecked Sendableneed a written invariant and an owner.- A module flips to Swift 6 mode once it's clean.
Read it in the app's source
Done with Swift 6 Concurrency? Mark it complete. Nailing its cards builds this pumpkin, row by row.