Swift 6 Concurrency & Actor Reentrancy: Production Pitfalls Cheat Sheet
Migrating an indie iOS codebase to Swift 6 strict concurrency eliminates data races at compile time, yet actor reentrancy remains the number-one logic bug teams hit in production. An actor protects mutual exclusion on its state, but every await inside an actor method suspends execution and allows other queued calls to enter and mutate state before the original call resumes.
The Classic Duplicate-Fetch Reentrancy Bug
If two views request the same cached image simultaneously, a naive dictionary check before await triggers two identical network requests. Storing the in-flight Task instead of only the finished value fixes reentrancy cleanly:
actor ImageStore {
private enum Entry {
case inProgress(Task<Data, Error>)
case ready(Data)
}
private var cache: [URL: Entry] = [:]
func data(for url: URL) async throws -> Data {
if let entry = cache[url] {
switch entry {
case .ready(let data): return data
case .inProgress(let task): return try await task.value
}
}
let task = Task { try await URLSession.shared.data(from: url).0 }
cache[url] = .inProgress(task)
do {
let result = try await task.value
cache[url] = .ready(result)
return result
} catch {
cache[url] = nil
throw error
}
}
}
Strict Concurrency Audit Matrix
| Symptom / Warning | Root Cause | Clean Fix |
|---|---|---|
| Duplicate API calls on cold start | Actor state checked before await without coalescing | Store in-flight Task in actor dictionary |
| UI stutter during JSON parsing | Heavy work running inside @MainActor function | Move decode step to a nonisolated helper or background actor |
| Task leaks after sheet dismissal | Unstructured Task {} not cancelled in deinit | Prefer SwiftUI .task(id:) or retain & cancel handle |
@unchecked Sendable crash | Mutable class property accessed across threads | Convert to value-type struct or wrap in OSAllocatedUnfairLock |
For the formal specification, consult the Swift Concurrency Language Guide.