SwiftPumpkin

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

await callresultstarts, cancelsonly SendableMain actorUI stateActorIsolated stateTask treeCancellable workSendable valuesCross boundaries
calls or tellsreports backEach piece of state has one isolation domain. Crossing domains takes an await and a Sendable value, checked at compile time.
  • 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.
PartOwnsLooks like
@MainActorUI state and anything touching UIKit or SwiftUI@MainActor @Observable
actorShared mutable state off the main threadactor ThanksRepository
SendableValues safe to share across domainsvalue types, immutable final classes
Structured tasksChild work that's cancelled with its parentasync let, TaskGroup, .task
Unstructured TaskBridge from sync code; you own cancellationTask { }, 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 @concurrent moves 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) or OSAllocatedUnfairLock avoids 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 threadAn actor, with synchronous critical sections.
Parallel workasync let for a fixed number of calls, a task group for a dynamic number.
BridgingTask {} from sync code, with a stored handle you cancel.

Compared

GCD vs Swift concurrency

GCDSwift concurrency
Data racesFound in testing, maybeCompile errors in Swift 6 mode
CancellationManual flagsBuilt into the task tree
Thread explosionPossible with blocking workCooperative pool sized to cores
Main-thread UIDispatch 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.

30-second answer

Explain Swift 6 Concurrency in 30 seconds.

SwiftAsked directly

Swift 6 makes data races compile errors. What concurrency bugs can you still ship?

iOS codingAsked indirectly

Search results flicker and sometimes show results for an older query. Walk through the fix.

System designAsked indirectly

You're migrating a large UIKit app to Swift 6 strict concurrency. How do you plan it?

Read it in the app's source

Done with Swift 6 Concurrency? Mark it complete. Nailing its cards builds this pumpkin, row by row.