skip to content

As iOS lead on a GCD-heavy app adopting Swift 6 language mode, which Dispatch and OperationQueue code would you move to async/await first, and which would you keep?

level: principalimportance: should knowfreq 30%

answer

  1. blocking waits come out first
  2. wait() unavailable from async code
  3. @Sendable closures, @preconcurrency warnings
  4. a literal main.async closure is main-actor
  5. keep the queues an API asks for

basics

~20 s

Move first the GCD code that blocks or guards shared state: semaphore and group waits, barrier-protected caches and main-queue hops for UI state. Keep queues an API requires, dispatch sources and working OperationQueue graphs, and wrap them at the boundary.

solid answer

~50 s

I rank by risk, not by count. First go the **blocking waits**: `DispatchSemaphore.wait()` and `DispatchGroup.wait()` cannot even be called from async code, since the overlay marks them unavailable there. Next, **shared mutable state** behind queues or barriers, and the **main-queue hops** that update UI state, because that is where Swift 6 checking pays off. What stays: serial queues an API takes as a parameter, dispatch sources, synchronous `concurrentPerform` loops, and OperationQueue graphs that work; each gets one async wrapper at its edge. One Swift 6.4 fact shapes the plan: closures passed to `DispatchQueue.async` are `@Sendable`, but the overlay declares the method `@preconcurrency`, so unsafe captures there are **warnings, not errors**, while the same capture in `Task.detached` is an error. A clean Swift 6 build is not a race-free one, so CI must fail on those warnings.

code

swift · 13 lines
swift
import Foundation

final class SkyCatalog {                   // not Sendable
    var names: [String] = []
}

func refresh(_ catalog: SkyCatalog) {
    DispatchQueue.global().async {
        // Swift 6 language mode, Swift 6.4: reported as a warning,
        // because DispatchQueue.async is declared @preconcurrency.
        catalog.names.append("Vega")
    }
}

go deeper

for a junior

Recall which GCD calls are blocking, semaphore and group waits, and that they cannot be called from async functions.

for a middle

Explain what the Swift 6 language mode checks in a closure sent to a queue, including that literal DispatchQueue.main.async closures are main-actor isolated.

for a senior

Find the risky code first: blocking waits, barrier-guarded caches and UI hops, and know that @preconcurrency turns their capture errors into warnings that still need fixing.

for a principal

Own the plan: rank subsystems by risk, decide what stays on queues behind one async entry point, and set CI and review rules so the migration does not leave silent races behind.

## The decision A codebase written before Swift concurrency usually has hundreds of `DispatchQueue` calls. Rewriting them all is expensive and risky; leaving them all means the Swift 6 language mode checks less than the team thinks. The lead's job is to decide **which GCD code moves first, which stays, and which rules stop new GCD debt**, using what the compiler and the SDK actually enforce. ## What the Swift 6 language mode checks in GCD code These facts come from the Dispatch overlay in the iOS 27.1 SDK and from compiling with Swift 6.4 in the Swift 6 language mode: - The closures taken by `async(group:qos:flags:execute:)` and `asyncAfter(deadline:qos:flags:execute:)` are `@Sendable`, so capturing a non-Sendable class or mutating a captured `var` inside them is diagnosed. - Those methods are declared `@preconcurrency`, and the incremental-migration rules downgrade such diagnostics from errors to warnings at those call sites, even in the Swift 6 language mode. The same capture passed to `Task.detached` is an error. - A closure written literally as `DispatchQueue.main.async { }` or `DispatchQueue.main.asyncAfter(deadline:) { }` is treated as main-actor isolated, so it may touch `@MainActor` state; the same closure sent through a queue stored in a variable is a plain `@Sendable` closure, and touching main-actor state in it is diagnosed. - `DispatchGroup.wait()` and `DispatchSemaphore.wait()` are unavailable from async contexts, with the messages "Use a TaskGroup instead" and "Await a Task handle instead"; OperationQueue's `waitUntilAllOperationsAreFinished()` points to `addBarrierBlock` or dependent operations. The consequence for planning: **a Swift 6 build with GCD warnings is not data-race safe**, and those warnings are where the remaining races live. ## Move first 1. **Blocking waits.** Semaphores used to make async callbacks look synchronous and group waits on background threads. They hold threads, risk deadlocks, and cannot be called from async code at all. Replace them with async functions; bridging a callback API is covered with continuations in the async functions material. 2. **Shared mutable state behind a queue or a barrier.** A thumbnail cache guarded by a concurrent queue with barrier writes is correct only by convention and usually carries `@unchecked Sendable`. Moving it under actor isolation, covered with actors, turns the convention into a compiler check. 3. **UI hops.** Code that updates view state through `DispatchQueue.main.async` is a natural fit for main-actor isolation of the view model, covered with actors. The compiler understands a literal main-queue closure, but a helper that receives the queue as a parameter loses that inference and produces warnings. 4. **Fan-out with DispatchGroup** that new features keep extending: a task group, covered with tasks, adds structured cancellation and error propagation. ## Keep, and wrap at the boundary - **Queues an API asks for**: frameworks that take a delegate or callback queue, and serial queues that confine a non-thread-safe C or Objective-C library. - **Dispatch sources**, such as timers and file-system monitoring, which keep working unchanged and rarely gain from a rewrite. - **Synchronous parallel loops** with `DispatchQueue.concurrentPerform(iterations:execute:)` in code that is itself synchronous. - **Working OperationQueue graphs** with dependencies, throttling and cancellation that nobody is changing; wrap the final completion once and leave the graph alone. Each kept subsystem exposes **one async entry point**, so callers never see the queue. ## A mapping the team can share | GCD or OperationQueue construct | Usual destination | Priority | |---|---|---| | `DispatchSemaphore.wait()` around a callback | an async function bridging the callback | first | | Barrier-guarded cache | actor isolation | high | | `DispatchQueue.main.async` for view state | main-actor view model | high | | `DispatchGroup` enter, leave, notify | task group | medium | | `DispatchWorkItem` debounce with `asyncAfter` | a cancellable task that sleeps | medium | | Delegate queues, dispatch sources | keep | none | | Stable `OperationQueue` dependency graph | keep, wrap at the edge | low | ## Rules to set while migrating - Fail CI on the Swift 6 concurrency warnings from GCD call sites, so the `@preconcurrency` downgrade does not hide races. - No new `DispatchSemaphore` or `DispatchGroup.wait()` anywhere, and no new `DispatchQueue.main.sync`. - New UI state goes behind main-actor isolation, not behind `DispatchQueue.main.async`. - Migrate one subsystem at a time, starting from the leaves of the dependency graph, and delete the old queue once its last caller moves. ## What not to do - Do not sprinkle async wrappers over every GCD call site: each wrapper adds a hop without adding a check. - Do not silence the GCD warnings with `@unchecked Sendable` on every class they mention; that marking is a promise the queue discipline must keep, and it hides the very races the migration is meant to find. - Do not keep two synchronisation schemes for one piece of state, such as a barrier queue and an actor, during a long transition; pick one per subsystem and switch in a single change.

  • Why is a clean Swift 6 build with GCD warnings not proof that the code is race-free?
    Because `DispatchQueue.async` is declared `@preconcurrency`, Swift 6.4 reports a non-Sendable capture or a captured `var` mutation in its closure as a warning, and the build still succeeds. The same capture in `Task.detached` is an error. Teams that ignore warnings ship those races, so the CI gate must treat them as failures.
  • Is DispatchQueue.main.async the same as hopping to the main actor?
    At run time both execute on the main thread. For the compiler, a closure written literally as `DispatchQueue.main.async { }` is treated as main-actor isolated, so it may touch `@MainActor` state; the same closure sent through a queue stored in a variable is a plain `@Sendable` closure and is diagnosed. Main-actor isolation on the type is checked everywhere, not only inside that one closure.
  • Which OperationQueue code would you leave alone?
    A stable pipeline whose steps depend on each other, throttle with `maxConcurrentOperationCount` and cancel cleanly. Rewriting it buys little and risks regressions. Give it one async entry point at its edge and revisit it only when the pipeline itself must change.

  • The Swift 6 language mode turns every unsafe GCD capture into a compile error.
  • Wrapping DispatchGroup.wait() inside an async function is a quick first migration step.
  • Every DispatchQueue must be removed before the Swift 6 language mode can be enabled.
  • DispatchQueue.main.async and main-actor isolation are equivalent, so neither needs review.
  • Rewriting a stable OperationQueue graph should come before fixing blocking semaphores.

Assumes Swift 6.4 in the Swift 6 language mode: Dispatch's @preconcurrency async methods report capture violations as warnings, not errors.