Skip to content
Commitwise
Menu
iOS Development

Migrating an app to Swift 6 concurrency

Move an existing iOS codebase to the Swift 6 language mode module by module, fix the common errors (global state, non-Sendable values, delegates and callbacks from other threads, legacy SDKs) without @unchecked shortcuts, and avoid the runtime isolation traps that only show up in production.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The team flips the app target to the Swift 6 language mode on a Friday afternoon. Xcode reports 1,400 errors. By Monday someone has added @unchecked Sendable to forty classes and nonisolated(unsafe) to every singleton, the errors are gone, and nothing is actually safer. Two weeks later, a crash appears that nobody has seen before: EXC_BREAKPOINT in _dispatch_assert_queue_fail, from inside a payment SDK’s callback.

The Swift concurrency lesson explains actors, Sendable and the main actor. This one is about the migration: doing it gradually, fixing each kind of error properly, and knowing the one class of problem that the compiler turns from silent bug into crash.

New to some of these? Open what you need, or skip ahead.

Basics:What is a data race?

A data race is two threads touching the same memory at the same time, with at least one of them writing. The result is unpredictable: wrong values, or a crash much later. Swift 6 checks your code at compile time so that data races can’t happen in it. See data raceData raceTwo threads accessing the same memory at the same time, at least one of them writing, without synchronization.Open in glossary →.

Basics:What are Sendable and @MainActor?

Sendable marks a type as safe to pass between threads: value types made of Sendable parts, actors, and immutable final classes. @MainActor marks code that must run on the main thread, like all UI code. The compiler uses both to decide what may cross from one thread to another. See sendableSendableA Swift protocol that marks values as safe to pass between concurrently running tasks and actors.Open in glossary → and actorActorA Swift type that protects its mutable state by running only one of its methods at a time.Open in glossary →.

Part Not started

A migration plan that works

Turning on Swift 6 for a whole app at once is like renovating every room of a house on the same day: nothing works until everything works. Instead, go room by room:

  1. One module at a time, starting with the ones that don’t depend on others (models, networking). In a single-target app, start with the checks as warnings.
  2. Turn on complete checking as warnings first: the “Strict Concurrency Checking: Complete” build setting while still in Swift 5 mode. The app still builds; you see every problem.
  3. Fix the warnings with the patterns in the next part.
  4. Switch that module to Swift 6. Now the same problems are errors, so they can’t come back.

Before fixing anything, decide where code should run, its isolation domainIsolation domainIn Swift concurrency, the region that owns some mutable state: an actor, the main actor, or nonisolated code.Open in glossary →. Most app code is UI or view models, so it belongs on the main actor. Shared data that many tasks touch goes in an actor. Plain data (structs of strings and numbers) is Sendable and can go anywhere.

Migrate per module, bottom-up: dependencies first, so upstream modules don’t have to absorb downstream annotations later. In each module, enable StrictConcurrency (complete checking) as warnings in the Swift 5 mode, drive warnings to zero, then set the Swift 6 language mode, which makes them errors and enables the dynamic isolation checks. Settle the isolation design first, since it determines most fixes: UI types and view models @MainActor (in Swift 6.2, defaultIsolation(MainActor.self) / “Default Actor Isolation” makes this implicit for app and UI modules, with nonisolated as the visible opt-out); shared mutable state in actors; domain values Sendable structs; CPU-heavy pure work nonisolated (with @concurrent under NonisolatedNonsendingByDefault). Use @preconcurrency import for dependencies that predate annotations (it downgrades their Sendable diagnostics; remove it when they update), and treat every @unchecked Sendable and nonisolated(unsafe) as a code-review item with a justification comment. Track progress as warnings per module in CI so the count only goes down.

// Package.swift (swift-tools-version: 6.2): per-target language modes and checks
.target(
    name: "Networking",
    swiftSettings: [.swiftLanguageMode(.v6)]                       // done: errors, no going back
),
.target(
    name: "ProfileFeature",
    dependencies: ["Networking", "DesignSystem"],
    swiftSettings: [
        .swiftLanguageMode(.v5),                                   // still migrating
        .enableUpcomingFeature("StrictConcurrency"),               // complete checking, as warnings
        .defaultIsolation(MainActor.self),                         // UI module: main actor unless stated
    ]
),
// A dependency that hasn't adopted Sendable yet: suppress its diagnostics, not yours
@preconcurrency import LegacyAnalyticsSDK
  • swiftLanguageMode(.v6) marks a module as finished: the compiler now rejects code that could race.
  • StrictConcurrency in Swift 5 mode shows the same problems as warnings, so the module keeps building while you fix them.
  • defaultIsolation(MainActor.self) (Swift 6.2) makes everything in the module run on the main actor unless marked otherwise, which is what UI code wants anyway. In Xcode it’s the Default Actor Isolation build setting.
  • @preconcurrency import quiets warnings that come from an older library you can’t change.
Spot the bugZero errors, no safety

Tap the line with the bug.

final class ImageCache: @unchecked Sendable {
    static let shared = ImageCache()
    private var images: [URL: UIImage] = [:]

    func image(for url: URL) -> UIImage? { images[url] }
    func store(_ image: UIImage, for url: URL) { images[url] = image }
}

Practice: plan the migration of a small app

A weather app has four parts: Models (structs), WeatherAPI (a class with a URLSession), LocationService (a class wrapping CLLocationManager) and the app target with SwiftUI views and view models.

  1. Models first: structs of String, Double and Date are Sendable automatically if they’re not public; public ones need : Sendable written out. Switch to Swift 6.
  2. WeatherAPI next: if it only holds let session: URLSession and a let base URL, make it a final class (or a struct) that is Sendable. Switch to Swift 6.
  3. LocationService: it receives delegate callbacks, so it needs the patterns from the next part. Warnings first, then fix.
  4. App target last: view models become @MainActor (or use the default-isolation setting), then switch to Swift 6.

Choosing isolation per type

TypeIsolation
Views, view models, coordinators, UI services@MainActor (or module default)
Caches, stores, token managers shared across tasksactor
Models, DTOs, configurationSendable structs and enums
Stateless clients holding Sendable dependenciesSendable final class or struct
CPU-heavy pure functionsnonisolated, @concurrent when it must leave the caller’s actor
Legacy classes with a lock you trust@unchecked Sendable + Mutex (iOS 18) with a comment, temporary

Mutex from the Synchronization module is Sendable and protects state without an actor’s async hop, which suits small synchronous critical sections.

  • Bottom-up per module: complete checking as warnings in Swift 5 mode → zero → Swift 6 mode. Track warnings per module in CI.
  • Isolation design first: UI on @MainActor (Swift 6.2 defaultIsolation(MainActor.self)), shared state in actors, data Sendable, CPU work nonisolated/@concurrent.
  • @preconcurrency import for un-annotated dependencies; remove later.
  • @unchecked Sendable and nonisolated(unsafe) need a real synchronization story (Mutex, serial queue) and a review comment.

Check this part

  1. What’s a safe first step for a big app moving to Swift 6?

  2. Where should a view model usually run?

  3. What does @preconcurrency import change?

  4. A class with a mutable dictionary is marked @unchecked Sendable to silence errors. Result?

Migrate per module, leaves first: enable complete concurrency checking as warnings in the Swift 5 mode, fix them, then switch that module to the Swift 6 language mode. Decide isolation up front: UI and view models on the main actor (Swift 6.2 can make it the default), shared mutable state in actors, plain data Sendable. Use @preconcurrency import for SDKs that aren't annotated yet, and don't silence errors with @unchecked Sendable.

Part Not started

Fixing the common errors

Most of the 1,400 errors are a handful of kinds, repeated:

  • “Static property ‘shared’ is not concurrency-safe”: a static var can be changed from any thread. Make it a let (the object inside must then be safe), or put it on the main actor.
  • “Sending ‘x’ risks causing data races” / “Capture of non-sendable type”: a value that isn’t safe to share is crossing to another thread. Make it a struct of safe values, or keep it on one actor.
  • “Main actor-isolated property can’t be referenced from a nonisolated context”: code that’s not on the main actor touches UI state. Mark the caller @MainActor, or await the access.
  • Delegate methods that can’t satisfy a protocol: a @MainActor class implements a delegate that Apple’s framework calls on another thread. Mark those methods nonisolated and hop to the main actor inside.

And one habit: replace completion handlers with async functions. Async code is much easier for the compiler (and for you) to check.

Common diagnostics and their proper fixes: global/static mutable state → let of a Sendable type, global-actor isolation, or an actor; nonisolated(unsafe) only with external synchronization. Non-Sendable values crossing domains → convert to Sendable values at the boundary (DTOs, ids instead of objects), keep the object inside one isolation domain, or use sending parameters and results where region analysis can prove the transfer. Delegates from Objective-C frameworks (CLLocationManagerDelegate, WKNavigationDelegate, SDK callbacks): a @MainActor type can’t satisfy nonisolated requirements, so mark the witnesses nonisolated and hop (Task { @MainActor in … }), use MainActor.assumeIsolated when the framework documents main-thread delivery (it traps otherwise), or in Swift 6.2 declare an isolated conformance (extension LocationService: @MainActor CLLocationManagerDelegate). Callback APIs → withCheckedContinuation or AsyncStream, isolating the bridge in one place. The trap to know: in the Swift 6 mode the compiler inserts dynamic isolation checks where a @MainActor closure or conformance is handed to code it can’t verify (@preconcurrency APIs, Objective-C); if that code calls it on a background queue, the app crashes with _dispatch_assert_queue_fail (“Incorrect actor executor assumption”) instead of silently racing. Test those paths, and annotate the closure parameters you own as @Sendable or non-main where they really run elsewhere.

// Before: Swift 5, minimal checking
final class LocationService: NSObject, CLLocationManagerDelegate {
    static var shared = LocationService()                  // error: global mutable state
    private let manager = CLLocationManager()
    var onUpdate: ((CLLocation) -> Void)?                  // callers juggle threads themselves

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        DispatchQueue.main.async { self.onUpdate?(locations.last!) }
    }
}

// After: Swift 6
@MainActor
final class LocationService: NSObject {
    static let shared = LocationService()                  // a let of a main-actor (so Sendable) type
    private let manager = CLLocationManager()              // created on the main thread: callbacks arrive there
    private(set) var lastLocation: CLLocation?
    private var continuation: AsyncStream<CLLocation>.Continuation?

    override init() {
        super.init()
        manager.delegate = self
    }

    /// Callers write: for await location in LocationService.shared.updates() { … }
    func updates() -> AsyncStream<CLLocation> {
        continuation?.finish()
        let (stream, continuation) = AsyncStream.makeStream(of: CLLocation.self)
        self.continuation = continuation
        manager.startUpdatingLocation()
        continuation.onTermination = { @Sendable _ in
            Task { @MainActor in LocationService.shared.manager.stopUpdatingLocation() }
        }
        return stream
    }

    fileprivate func receive(_ location: CLLocation) {
        lastLocation = location
        continuation?.yield(location)
    }
}

extension LocationService: CLLocationManagerDelegate {
    // The protocol isn't main-actor isolated, so the witness is nonisolated and hops explicitly.
    nonisolated func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        Task { @MainActor in self.receive(location) }
    }
}
  • static let shared fixes the global-state error: a let can’t be reassigned, and the class is on the main actor, so it’s safe to share.
  • nonisolated func locationManager says “this method may be called from any thread”, which is the truth for a delegate. Inside, Task { @MainActor in … } moves the work to the main actor, where the class’s state lives.
  • AsyncStream replaces the onUpdate closure: callers use for await, and stopping the loop stops location updates.
  • No !: the old code force-unwrapped locations.last, which would crash on an empty array.

Predict the output

In Swift 6 mode, a class marked @MainActor has: nonisolated func didFinish() { status = "done" }, where status is a normal stored property of the class. What does the compiler say?

Production puzzles

Predict the output

After switching the app target to Swift 6, a @MainActor view model passes a closure to a payment SDK (an Objective-C framework imported with @preconcurrency): sdk.authorize(amount) { result in self.state = .done(result) }. The SDK calls the completion on its own background queue. What happens in production?

Spot the bugA token store that compiles

Tap the line with the bug.

actor TokenStore {
    private var token: String?
    private var refreshTask: Task<String, Error>?

    func validToken() async throws -> String {
        if let token, !isExpired(token) { return token }
        let fresh = try await api.refresh()
        token = fresh
        return fresh
    }
}

Exercisehard

Unblock a stuck migration

A feature module has 300 warnings left. Most come from a UserSession class (a NotificationCenter observer, a mutable user property, a DispatchQueue for disk writes) used from view models, a background sync service and an app extension. Propose a design and the order of changes.

›

Who reads and writes UserSession, from which isolation domains, and what must cross between them?

SolutionTry it yourself first
  • Split the state from the side effects. The current user is a Sendable User struct. Persisting it is a separate UserStore actor that owns the file I/O (replacing the private queue), used by the app and the extension through the App Group.
  • UI-facing state: an @Observable @MainActor SessionModel that holds the current User for views, updated from the store.
  • Change notifications: replace NotificationCenter with an AsyncStream<User?> exposed by the store (or the typed NotificationCenter messages in newer SDKs); the session model and the sync service each iterate it in their own isolation.
  • Background sync talks to the actor with await, passing and receiving User values only.
  • Order: make User Sendable (removes the bulk of the warnings), introduce the UserStore actor behind the old API, move callers one by one, delete the old class, then switch the module to Swift 6.
  • Verify: TSan on the sync tests, and a test that two concurrent writes don’t lose an update.
Exercisemedium

Turn a completion handler into async

WeatherAPI has func forecast(for city: String, completion: @escaping (Result<Forecast, Error>) -> Void), which calls the completion on a background queue. A @MainActor view model calls it and sets self.forecast in the completion, which now gives Swift 6 errors. Fix it.

›

Give the API an async throws version, then call it from the view model with await.

SolutionTry it yourself first
extension WeatherAPI {
    func forecast(for city: String) async throws -> Forecast {
        try await withCheckedThrowingContinuation { continuation in
            forecast(for: city) { result in
                continuation.resume(with: result)      // the thread it's called on doesn't matter
            }
        }
    }
}

@MainActor @Observable
final class WeatherModel {
    private(set) var forecast: Forecast?
    private(set) var errorMessage: String?
    let api: WeatherAPI

    init(api: WeatherAPI) { self.api = api }

    func load(city: String) async {
        do {
            forecast = try await api.forecast(for: city)   // back on the main actor after await
        } catch {
            errorMessage = "Couldn’t load the forecast."
        }
    }
}

After await, the view model’s code continues on the main actor, because the class is @MainActor. No DispatchQueue.main.async is needed, and Forecast must be Sendable to cross back.

  • Global/static state: let + Sendable, global actor, or actor; nonisolated(unsafe) only with real synchronization.
  • Crossing domains: convert to Sendable values (ids, DTOs) at the boundary; sending where region analysis proves transfer.
  • Delegates: nonisolated witnesses + explicit hop; MainActor.assumeIsolated when main-thread delivery is documented (traps otherwise); Swift 6.2 isolated conformances (@MainActor P).
  • Callbacks → continuations / AsyncStream, bridged once.
  • Swift 6 inserts dynamic isolation checks for main-actor closures given to unverified APIs: background calls crash with _dispatch_assert_queue_fail. Mark such closures @Sendable and hop.
  • No data races ≠ no logic races: actor reentrancy across await remains.

Check this part

  1. How do you fix "static property shared is not concurrency-safe" for a main-actor service?

  2. A delegate method is called by Apple’s framework on a background thread. How does a @MainActor class handle it?

  3. In Swift 6 mode, a main-actor closure is called by an Objective-C SDK on a background queue. Result?

  4. Can an actor still have race-like bugs in Swift 6?

Global and static vars become let constants of Sendable types, main-actor isolated, or actors. Non-Sendable values stay inside one isolation domain or become Sendable values. Delegates and callbacks from other threads use nonisolated methods that hop to the main actor (or isolated conformances in Swift 6.2); callback APIs become async with continuations or AsyncStream. In Swift 6 mode, @MainActor closures passed to legacy APIs are checked at runtime and trap if called off the main thread.

Key takeaways

  • Migrate one module at a time: warnings first, then the Swift 6 mode.
  • Decide where code runs: UI on the main actor, shared state in actors, data as Sendable structs.
  • Don’t silence errors with @unchecked Sendable; fix the race.
  • Delegates called from other threads: nonisolated methods that hop to the main actor.
  • Replace completion handlers with async functions.
  • Design isolation first; most errors then have one obvious fix.
  • Bridge legacy APIs once, at the edge, with continuations and AsyncStream.
  • Expect runtime isolation traps where unverified code calls main-actor closures; test those paths.
  • Reentrancy and logic races remain your job after the compiler is happy.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.