Swift Concurrency
Overview
This skill provides expert guidance on Swift Concurrency, covering modern async/await patterns, actors, tasks, Sendable conformance, and migration to Swift 6. Use this skill to help developers write safe, performant concurrent code and navigate the complexities of Swift's structured concurrency model.
Agent Behavior Contract (Follow These Rules)
- Analyze the project/package file to find out which Swift language mode (Swift 5.x vs Swift 6) and which Xcode/Swift toolchain is used when advice depends on it.
- Before proposing fixes, identify the isolation boundary: , custom actor, actor instance isolation, or nonisolated.
- Do not recommend as a blanket fix. Justify why main-actor isolation is correct for the code.
- Prefer structured concurrency (child tasks, task groups) over unstructured tasks. Use only with a clear reason.
- If recommending , , or , require:
- a documented safety invariant
- a follow-up ticket to remove or migrate it
- For migration work, optimize for minimal blast radius (small, reviewable changes) and add verification steps.
- Course references are for deeper learning only. Use them sparingly and only when they clearly help answer the developer’s question.
Project Settings Intake (Evaluate Before Advising)
Concurrency behavior depends on build settings. Always try to determine:
- Default actor isolation (is the module default or ?)
- Strict concurrency checking level (minimal/targeted/complete)
- Whether upcoming features are enabled (especially
NonisolatedNonsendingByDefault
)
- Swift language mode (Swift 5.x vs Swift 6) and SwiftPM tools version
Manual checks (no scripts)
- SwiftPM:
- Check for
.defaultIsolation(MainActor.self)
.
- Check for
.enableUpcomingFeature("NonisolatedNonsendingByDefault")
.
- Check for strict concurrency flags:
.enableExperimentalFeature("StrictConcurrency=targeted")
(or similar).
- Check tools version at the top:
// swift-tools-version: ...
- Xcode projects:
- Search for:
SWIFT_DEFAULT_ACTOR_ISOLATION
- (and/or
SWIFT_ENABLE_EXPERIMENTAL_FEATURES
)
If any of these are unknown, ask the developer to confirm them before giving migration-sensitive guidance.
Quick Decision Tree
When a developer needs concurrency guidance, follow this decision tree:
-
Starting fresh with async code?
- Read
references/async-await-basics.md
for foundational patterns
- For parallel operations → (async let, task groups)
-
Protecting shared mutable state?
- Need to protect class-based state → (actors, @MainActor)
- Need thread-safe value passing → (Sendable conformance)
-
Managing async operations?
- Structured async work → (Task, child tasks, cancellation)
- Streaming data →
references/async-sequences.md
(AsyncSequence, AsyncStream)
-
Working with legacy frameworks?
- Core Data integration →
- General migration →
-
Performance or debugging issues?
- Slow async code →
references/performance.md
(profiling, suspension points)
- Testing concerns → (XCTest, Swift Testing)
-
Understanding threading behavior?
- Read for thread/task relationship and isolation
-
Memory issues with tasks?
- Read
references/memory-management.md
for retain cycle prevention
Triage-First Playbook (Common Errors -> Next Best Move)
- SwiftLint concurrency-related warnings
- Use for rule intent and preferred fixes; avoid dummy awaits as “fixes”.
- SwiftLint warning
- Remove if not required; if required by protocol/override/@concurrent, prefer narrow suppression over adding fake awaits. See .
- "Sending value of non-Sendable type ... risks causing data races"
- First: identify where the value crosses an isolation boundary
- Then: use and (especially Swift 6.2 behavior changes)
- "Main actor-isolated ... cannot be used from a nonisolated context"
- First: decide if it truly belongs on
- Then: use (global actors, , isolated parameters) and (default isolation)
- "Class property 'current' is unavailable from asynchronous contexts" (Thread APIs)
- Use to avoid thread-centric debugging and rely on isolation + Instruments
- XCTest async errors like "wait(...) is unavailable from asynchronous contexts"
- Use ( and Swift Testing patterns)
- Core Data concurrency warnings/errors
- Use (DAO/, default isolation conflicts)
Core Patterns Reference
When to Use Each Concurrency Tool
async/await - Making existing synchronous code asynchronous
swift
// Use for: Single asynchronous operations
func fetchUser() async throws -> User {
try await networkClient.get("/user")
}
async let - Running multiple independent async operations in parallel
swift
// Use for: Fixed number of parallel operations known at compile time
async let user = fetchUser()
async let posts = fetchPosts()
let profile = try await (user, posts)
Task - Starting unstructured asynchronous work
swift
// Use for: Fire-and-forget operations, bridging sync to async contexts
Task {
await updateUI()
}
Task Group - Dynamic parallel operations with structured concurrency
swift
// Use for: Unknown number of parallel operations at compile time
await withTaskGroup(of: Result.self) { group in
for item in items {
group.addTask { await process(item) }
}
}
Actor - Protecting mutable state from data races
swift
// Use for: Shared mutable state accessed from multiple contexts
actor DataCache {
private var cache: [String: Data] = [:]
func get(_ key: String) -> Data? { cache[key] }
}
@MainActor - Ensuring UI updates on main thread
swift
// Use for: View models, UI-related classes
@MainActor
class ViewModel: ObservableObject {
@Published var data: String = ""
}
Common Scenarios
Scenario: Network request with UI update
swift
Task { @concurrent in
let data = try await fetchData() // Background
await MainActor.run {
self.updateUI(with: data) // Main thread
}
}
Scenario: Multiple parallel network requests
swift
async let users = fetchUsers()
async let posts = fetchPosts()
async let comments = fetchComments()
let (u, p, c) = try await (users, posts, comments)
Scenario: Processing array items in parallel
swift
await withTaskGroup(of: ProcessedItem.self) { group in
for item in items {
group.addTask { await process(item) }
}
for await result in group {
results.append(result)
}
}
Swift 6 Migration Quick Guide
Key changes in Swift 6:
- Strict concurrency checking enabled by default
- Complete data-race safety at compile time
- Sendable requirements enforced on boundaries
- Isolation checking for all async boundaries
For detailed migration steps, see
.
Reference Files
Official Apple Documentation:
Swift-Concurrency-Updates.md
- Official Apple documentation on Swift 6.2 data-race safety, Approachable Concurrency, default actor isolation, and new concurrency features
Community Course References:
Load these files as needed for specific topics:
- - async/await syntax, execution order, async let, URLSession patterns
- - Task lifecycle, cancellation, priorities, task groups, structured vs unstructured
- - Thread/task relationship, suspension points, isolation domains, nonisolated
- - Retain cycles in tasks, memory safety patterns
- - Actor isolation, @MainActor, global actors, reentrancy, custom executors, Mutex
- - Sendable conformance, value/reference types, @unchecked, region isolation
- - Concurrency-focused lint rules and SwiftLint
- - AsyncSequence, AsyncStream, when to use vs regular async methods
- - NSManagedObject sendability, custom executors, isolation conflicts
- - Profiling with Instruments, reducing suspension points, execution strategies
- - XCTest async patterns, Swift Testing, concurrency testing utilities
- - Swift 6 migration strategy, closure-to-async conversion, @preconcurrency, FRP migration
Best Practices Summary
- Prefer structured concurrency - Use task groups over unstructured tasks when possible
- Minimize suspension points - Keep actor-isolated sections small to reduce context switches
- Use @MainActor judiciously - Only for truly UI-related code
- Make types Sendable - Enable safe concurrent access by conforming to Sendable
- Handle cancellation - Check Task.isCancelled in long-running operations
- Avoid blocking - Never use semaphores or locks in async contexts
- Test concurrent code - Use proper async test methods and consider timing issues
Verification Checklist (When You Change Concurrency Code)
- Confirm build settings (default isolation, strict concurrency, upcoming features) before interpreting diagnostics.
- After refactors:
- Run tests, especially concurrency-sensitive ones (see ).
- If performance-related, verify with Instruments (see
references/performance.md
).
- If lifetime-related, verify deinit/cancellation behavior (see
references/memory-management.md
).
Glossary
See
for quick definitions of core concurrency terms used across this skill.
Note: This skill is based on the comprehensive
Swift Concurrency Course by Antoine van der Lee.