Expert guidance on Swift Concurrency best practices, patterns, and implementation. Use when developers mention: (1) Swift Concurrency, async/await, actors, or tasks, (2) "use Swift Concurrency" or "modern concurrency patterns", (3) migrating to Swift 6, (4) data races or thread safety issues, (5) refactoring closures to async/await, (6) @MainActor, Sendable, or actor isolation, (7) concurrent code architecture or performance optimization.
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.
@MainActor, custom actor, actor instance isolation, or nonisolated.@MainActor as a blanket fix. Justify why main-actor isolation is correct for the code.Task.detached only with a clear reason.@preconcurrency, @unchecked Sendable, or nonisolated(unsafe), require:
Concurrency behavior depends on build settings. Always try to determine:
@MainActor or nonisolated?)NonisolatedNonsendingByDefault)Package.swift for .defaultIsolation(MainActor.self).Package.swift for .enableUpcomingFeature("NonisolatedNonsendingByDefault")..enableExperimentalFeature("StrictConcurrency=targeted") (or similar).// swift-tools-version: ...project.pbxproj for:
SWIFT_DEFAULT_ACTOR_ISOLATIONSWIFT_STRICT_CONCURRENCYSWIFT_UPCOMING_FEATURE_ (and/or SWIFT_ENABLE_EXPERIMENTAL_FEATURES)If any of these are unknown, ask the developer to confirm them before giving migration-sensitive guidance.
When a developer needs concurrency guidance, follow this decision tree:
Starting fresh with async code?
references/async-await-basics.md for foundational patternsreferences/tasks.md (async let, task groups)Protecting shared mutable state?
references/actors.md (actors, @MainActor)references/sendable.md (Sendable conformance)Managing async operations?
references/tasks.md (Task, child tasks, cancellation)references/async-sequences.md (AsyncSequence, AsyncStream)Working with legacy frameworks?
references/core-data.mdreferences/migration.mdPerformance or debugging issues?
references/performance.md (profiling, suspension points)references/testing.md (XCTest, Swift Testing)Understanding threading behavior?
references/threading.md for thread/task relationship and isolationMemory issues with tasks?
references/memory-management.md for retain cycle preventionreferences/sendable.md and references/threading.md (especially Swift 6.2 behavior changes)@MainActorreferences/actors.md (global actors, nonisolated, isolated parameters) and references/threading.md (default isolation)references/threading.md to avoid thread-centric debugging and rely on isolation + Instrumentsreferences/testing.md (await fulfillment(of:) and Swift Testing patterns)references/core-data.md (DAO/NSManagedObjectID, default isolation conflicts)async/await - Making existing synchronous code asynchronous
// Use for: Single asynchronous operations
func fetchUser() async throws -> User {
try await networkClient.get("/user")
}
async let - Running multiple independent async operations in parallel
// 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
// Use for: Fire-and-forget operations, bridging sync to async contexts
Task {
await updateUI()
}
Task Group - Dynamic parallel operations with structured concurrency
// 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
// 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
// Use for: View models, UI-related classes
@MainActor
class ViewModel: ObservableObject {
@Published var data: String = ""
}
Scenario: Network request with UI update
Task { @concurrent in
let data = try await fetchData() // Background
await MainActor.run {
self.updateUI(with: data) // Main thread
}
}
Scenario: Multiple parallel network requests
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
await withTaskGroup(of: ProcessedItem.self) { group in
for item in items {
group.addTask { await process(item) }
}
for await result in group {
results.append(result)
}
}
Key changes in Swift 6:
For detailed migration steps, see references/migration.md.
Load these files as needed for specific topics:
async-await-basics.md - async/await syntax, execution order, async let, URLSession patternstasks.md - Task lifecycle, cancellation, priorities, task groups, structured vs unstructuredthreading.md - Thread/task relationship, suspension points, isolation domains, nonisolatedmemory-management.md - Retain cycles in tasks, memory safety patternsactors.md - Actor isolation, @MainActor, global actors, reentrancy, custom executors, Mutexsendable.md - Sendable conformance, value/reference types, @unchecked, region isolationasync-sequences.md - AsyncSequence, AsyncStream, when to use vs regular async methodscore-data.md - NSManagedObject sendability, custom executors, isolation conflictsperformance.md - Profiling with Instruments, reducing suspension points, execution strategiestesting.md - XCTest async patterns, Swift Testing, concurrency testing utilitiesmigration.md - Swift 6 migration strategy, closure-to-async conversion, @preconcurrency, FRP migrationreferences/testing.md).references/performance.md).references/memory-management.md).See references/glossary.md 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.