20 of 22 · 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 | structs, enums, 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 var task: Task<Void, Never>?
func queryChanged(_ text: String) {
task?.cancel() // a newer query supersedes the old one
task = Task {
guard let found = try? await api.search(text) else { return }
guard !Task.isCancelled else { return } // superseded while awaiting
results = found
}
}
}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
}
}
// In production, bound this (LRU or NSCache) so it can't grow forever.
}Both snippets assume an api and a download function defined elsewhere.
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: state lives in one isolation domain, and only Sendable values cross.
- The bugs that remain are logical: reentrancy across awaits and forgotten cancellation.
- So I keep UI state on the main actor, cancel superseded work, and re-check invariants after every await.
Swift 6 makes data races compile errors. What concurrency bugs can you still ship?
- Logic races.
- Actor reentrancy: state changes across an
await, so read-await-write sequences break. - Missing cancellation: superseded work still finishes and publishes stale results.
- Work on the wrong executor: a
Task {}from the main actor inherits it. - And deadlock-like stalls from blocking calls inside the cooperative pool.
- The compiler checks isolation, not intent.
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?
- Module by module, leaves first, with the Swift 6 language mode on per module.
- Make UI types
@MainActorexplicitly, or adopt default main-actor isolation for app targets. - Convert shared mutable singletons into actors or main-actor types.
- Allow
@preconcurrencyand@unchecked Sendableonly with a written invariant and an owner, tracked so they get removed. - Keep each step shippable.