All Articles
CategorySwift
Reading Time
15 min read
Published
2026-05-13
Word Count
1,859words

Grab a coffee — this one is a deep dive!3 views

Swift 6 Strict Concurrency: Production Migration Playbook

Summary

From the strict concurrency mode opt-in flag to production-ready code — 12 common pitfalls, fixes, and the actor migration order for moving a large iOS codebase to strict concurrency.

  • On a large codebase the migration can stretch over months; measure build time, launch time and memory in your own app before and after.
  • Actor migration order: stateless services, stateful services, DI container, ViewModels, Views.
  • Breaking the single-resume rule in withCheckedThrowingContinuation causes a crash or an infinite wait.
  • Make only the UI-bound method @MainActor, not the whole class; compare crash analytics before and after the migration.
Swift 6 Strict Concurrency: Production Migration Playbook

Swift 6.0's strict concurrency looks, at first glance, like an opt-in compile flag. But in reality? It's a serious refactor mandate touching every one of your classes, singletons, delegate patterns, and dependency-injection architecture.

This article walks through the 12 common pitfalls you are likely to hit when moving a large production iOS codebase to strict concurrency mode, their fixes, and the correct actor migration order. Spoiler: @MainActor is not the cure for everything.

Pro Tip: Before starting the migration, don't begin with SWIFT_STRICT_CONCURRENCY = complete — start with targeted. Targeted mode only checks Sendable; complete mode also enforces actor isolation. Starting targeted cuts your first-pass error count in half.

Table of Contents

  1. The Three Levels of Strict Concurrency Mode
  2. Sendable: The End of Invisible Leaks
  3. Actor Migration Order: The Right Way
  4. @MainActor Pitfalls (5 of the 12)
  5. Async/Await and Existing Callback Patterns
  6. Does the Singleton Pattern Survive Strict Concurrency?
  7. Delegate Pattern → AsyncSequence Migration
  8. Test Mocking + Sendable
  9. Production Profiling: The Performance Trade-off
  10. Migration Checklist

1. The Three Levels of Strict Concurrency Mode

Swift 6 strict concurrency is controlled by the SWIFT_STRICT_CONCURRENCY build setting, and it has three levels:

bash
1# Minimal — Swift 5.x default behavior
2SWIFT_STRICT_CONCURRENCY = minimal
3 
4# Targeted — only Sendable explicit marked types check
5SWIFT_STRICT_CONCURRENCY = targeted
6 
7# Complete — full Swift 6 strict concurrency
8SWIFT_STRICT_CONCURRENCY = complete

Practical migration strategy:

  1. Weeks 1-2: Move the whole project from minimal to targeted. Fix Sendable warnings.
  2. Weeks 3-4: Turn on complete mode module by module. The UI layer goes last.
  3. Week 5: Full project on complete. Swift 6 language mode active.

Migrating small modules first (Networking, Persistence) reduces production risk — changes that leak into the UI layer are usually the most expensive.


2. Sendable: The End of Invisible Leaks

A large share of the migration work comes down to Sendable conformance. A type being Sendable means it's safe to share across multiple threads.

swift
1// ❌ Strict mode error: User isn't Sendable
2class User {
3 var name: String
4 var preferences: [String: Any] // [String: Any] isn't Sendable!
5}
6 
7// ✅ Solution: struct + typed properties
8struct User: Sendable {
9 let id: UUID
10 let name: String
11 let preferences: UserPreferences // Sendable Codable struct
12}

Common Sendable pitfalls:

  • [String: Any] — Any isn't Sendable; use a typed dictionary
  • URL — Sendable ✓, URLRequest Sendable ✓
  • Date — Sendable ✓ (Swift 5.5+)
  • UIImage — not Sendable (reference type, mutable)
  • NSData — not Sendable; Data is Sendable ✓
  • Closure types — require the @Sendable annotation
Pro Tip: Don't try to make legacy Objective-C types (NSObject subclasses) Sendable — they're reference types and mutable. Wrap them in a pure-Swift struct instead.

3. Actor Migration Order: The Right Way

Actors are the gold standard for concurrent state in Swift 6. But migrating them in the wrong order means walking into a maze of rework. Recommended order:

  1. Stateless services (URLSession wrapper, JSON decoder) — not an actor, use struct or enum with static methods
  2. Stateful services (cache, session manager) — make them an actor
  3. DI container / service locator — global state, actor or @MainActor class
  4. ViewModels — @MainActor (they have a UI dependency)
  5. Views — SwiftUI is already MainActor-isolated
swift
1// Stateful cache → actor (Correct)
2actor ImageCache {
3 private var cache: [URL: UIImage] = [:]
4 
5 func image(for url: URL) -> UIImage? {
6 cache[url]
7 }
8 
9 func setImage(_ image: UIImage, for url: URL) {
10 cache[url] = image
11 }
12}
13 
14// Usage: await required
15let image = await imageCache.image(for: url)

Pitfall: don't try to preserve your old synchronous APIs when converting to actor. Every public method becomes async. If call sites are too scattered, use a transition wrapper:

swift
1@MainActor
2final class ImageCacheBridge {
3 private let cache: ImageCache
4 
5 nonisolated func imageSync(for url: URL) -> UIImage? {
6 // Sync fallback for legacy paths (deprecated)
7 return MainActor.assumeIsolated {
8 self.legacyCacheStorage[url]
9 }
10 }
11}

4. @MainActor Pitfalls

@MainActor is the most powerful tool for UIKit/SwiftUI interop. But misuse hurts performance badly.

Pitfall 1: Marking the entire class @MainActor

swift
1// ❌ Wrong — JSON parsing blocks the main thread
2@MainActor
3final class APIClient {
4 func fetchUsers() async throws -> [User] {
5 let data = try await URLSession.shared.data(from: usersURL).0
6 return try JSONDecoder().decode([User].self, from: data) // 200ms main thread block!
7 }
8}
9 
10// ✅ Correct — only UI-bound method @MainActor
11final class APIClient {
12 nonisolated func fetchUsers() async throws -> [User] {
13 let data = try await URLSession.shared.data(from: usersURL).0
14 return try JSONDecoder().decode([User].self, from: data)
15 }
16 
17 @MainActor
18 func updateUI(with users: [User]) {
19 // UI update logic
20 }
21}

Pitfall 2: Incorrectly capturing values in @MainActor closures

swift
1Task { @MainActor in
2 // This whole block runs on the main thread — don't do heavy work here!
3 let processed = self.heavyProcessing() // main blocking!
4 self.updateView(with: processed)
5}
6 
7// ✅ Correct — heavy work in background, only UI update on main
8Task {
9 let processed = await self.heavyProcessing() // arbitrary executor
10 await MainActor.run {
11 self.updateView(with: processed)
12 }
13}

Pitfall 3: MainActor.assumeIsolated is for synchronous compatibility, but misuse causes a runtime crash. Only use it where you can guarantee the code is already running on the main thread.


5. Async/Await and Existing Callback Patterns

A large, older codebase can easily have hundreds of closure-based APIs. Migrating all of them to async/await at once isn't feasible.

Bridge pattern:

swift
1// Old callback API
2func fetchData(completion: @escaping (Result<Data, Error>) -> Void) {
3 // legacy code
4}
5 
6// Async wrapper
7func fetchData() async throws -> Data {
8 try await withCheckedThrowingContinuation { continuation in
9 fetchData { result in
10 continuation.resume(with: result)
11 }
12 }
13}

Watch out — withCheckedThrowingContinuation pitfalls:

  • The continuation is one-shot — resuming it twice by mistake crashes
  • If you store the closure and never resume it, the async caller hangs forever
  • Cancellation handling must be explicit — use withTaskCancellationHandler

In production, use @CheckedContinuation to catch continuation leaks (Swift 6 default, has a debug check).


6. Does the Singleton Pattern Survive Strict Concurrency?

You're told singletons are an anti-pattern, but in a codebase with 200K LOC and 8 years of history, they exist and aren't going anywhere. How do they survive strict concurrency?

swift
1// ❌ Strict mode error
2class AnalyticsTracker {
3 static let shared = AnalyticsTracker() // mutable global state warning
4 var sessionID: String = UUID().uuidString
5}
6 
7// ✅ Solution 1: actor
8actor AnalyticsTracker {
9 static let shared = AnalyticsTracker()
10 var sessionID: String = UUID().uuidString
11 
12 func setSession(_ id: String) {
13 sessionID = id
14 }
15}
16 
17// ✅ Solution 2: immutable
18final class AnalyticsTracker: Sendable {
19 static let shared = AnalyticsTracker()
20 let sessionID = UUID().uuidString // immutable, Sendable safe
21 private init() {}
22}

Decision matrix:

  • Internal state gets mutated → actor
  • Pure read-only → Sendable final class
  • UI-bound singleton → @MainActor final class

7. Delegate Pattern → AsyncSequence Migration

Most Apple frameworks are delegate-based. Under strict concurrency, delegate methods need Sendable conformance.

swift
1// Old pattern
2class LocationTracker: NSObject, CLLocationManagerDelegate {
3 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
4 // delegate callback
5 }
6}
7 
8// Modern pattern — AsyncSequence
9class LocationTracker {
10 var locations: AsyncStream<CLLocation> {
11 AsyncStream { continuation in
12 let bridge = LocationBridge { location in
13 continuation.yield(location)
14 }
15 // CLLocationManager setup
16 }
17 }
18}
19 
20// Usage — clean
21for await location in tracker.locations {
22 await viewModel.updateLocation(location)
23}

This pattern works the same way for MapKit, BLE, Camera, and Audio — wrap the old delegates in an AsyncStream.


8. Test Mocking + Sendable

Test mocks need to be Sendable, otherwise tests fail under the concurrent runner.

swift
1// Test double — Sendable conform
2final class MockUserService: UserServicing, Sendable {
3 let stubUsers: [User]
4 
5 init(users: [User] = []) {
6 self.stubUsers = users
7 }
8 
9 func fetchUsers() async throws -> [User] {
10 stubUsers
11 }
12}

Pro Tip: XCTest's default test parallelization does a Sendable check. If a test class holds state, mark it @MainActor or move that state into an actor.


9. Production Profiling: The Performance Trade-off

Strict concurrency isn't free. Actor hops add a small cost to every async call. These are the metrics to compare in your own app before and after the migration:

Metric
Why it matters
How to measure
Launch time
Actor hops added to the main thread can delay the first screen
Instruments App Launch template + MetricKit
Memory baseline
Extra tasks and actor objects can raise the memory floor
Xcode Memory Report + MetricKit
CPU under load
Frequent actor hops can raise CPU share in busy flows
Instruments Time Profiler
Build time
Complete mode makes type checking heavier and builds slower
Xcode Build Timeline

Build time is usually the most noticeable increase. Fix: incremental build caching and modularization.

Runtime overhead stays negligible for most mobile apps; still, verify hot paths with Time Profiler.

On the crash side, the expected gain is that data races closed at compile time no longer surface as runtime crashes; measure the effect by comparing crash analytics before and after the migration.


10. Migration Checklist

A recommended sequential checklist for migrating a production app:

  • Phase 0: Project on SWIFT_STRICT_CONCURRENCY = targeted, clean build
  • Phase 1: Migrate the networking layer, Sendable conformance
  • Phase 2: Persistence layer (Core Data, SwiftData) actor migration
  • Phase 3: Service container (DI) as actor or @MainActor
  • Phase 4: Mark ViewModels @MainActor
  • Phase 5: Mark UIKit ViewControllers @MainActor (SwiftUI views already are)
  • Phase 6: Turn on SWIFT_STRICT_CONCURRENCY = complete
  • Phase 7: Swift 6 language mode (SWIFT_VERSION = 6)
  • Phase 8: Enforce strict mode in the CI/CD pipeline
  • Phase 9: Two weeks of crash-analytics observation
  • Phase 10: Publish the performance baseline
Pro Tip: Don't do the migration on a feature branch — go gradual on main. On a large codebase the migration can take weeks or even months, so conflicts on a long-lived branch are unavoidable. Merging module-by-module into main is far more sustainable.

Conclusion

Strict concurrency is the delivery on Swift's 8-year-old safety promise. The ability to catch data races at compile time is valuable because it closes this class of runtime crashes at the source. But the migration isn't cheap — on a large codebase, budget for effort that can stretch over months, noticeably longer build times, and a small runtime overhead.

The pragmatic call: for new projects, Swift 6 + complete strict concurrency by default. For existing projects, a targeted → complete transition on a phased, module-by-module plan. @MainActor isn't the cure for everything; used correctly, it means keeping heavy work off the main thread with nonisolated.

Related resources:

Tags

#Swift 6#concurrency#migration#iOS#actor#Sendable#production
Muhittin Camdali

Muhittin Çamdalı

Senior Mobile Engineer

Senior Mobile Engineer with 12+ years of experience. I build mobile products with iOS, Flutter and React Native, working full-stack and AI-native.

iOS Development News

Weekly Swift tips, SwiftUI tricks and iOS best practices. No spam, only valuable content.

Your subscription starts when you open the link in the confirmation email and press “Confirm my subscription”. The newsletter keeps open/click statistics; you can unsubscribe anytime with one click. Privacy

Share