swift-concurrency
Diagnose data races, convert callback-based code to async/await, implement actor isolation patterns, resolve Sendable conformance issues, and guide Swift 6 migration. 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, (8) concurrency-related linter warnings (SwiftLint or similar; e.g. async_without_await, Sendable/actor isolation/MainActor lint).
git clone https://github.com/AvdLee/Swift-Concurrency-Agent-Skill
T=$(mktemp -d) && git clone --depth=1 https://github.com/AvdLee/Swift-Concurrency-Agent-Skill "$T" && mkdir -p ~/.claude/skills && cp -r "$T/swift-concurrency" ~/.claude/skills/avdlee-swift-concurrency-agent-skill-swift-concurrency && rm -rf "$T"
swift-concurrency/SKILL.mdSwift Concurrency
Fast Path
Before proposing a fix:
- Analyze
orPackage.swift
to determine Swift language mode, strict concurrency level, default isolation, and upcoming features. Do this always, not only for migration work..pbxproj - Capture the exact diagnostic and offending symbol.
- Determine the isolation boundary:
, custom actor, actor instance isolation, or@MainActor
.nonisolated - Confirm whether the code is UI-bound or intended to run off the main actor. For delayed retries, timers, and backoff tasks, separate the waiting from the UI mutation. The sleep often belongs off the main actor even when the final state update belongs on it.
Project settings that change concurrency behavior:
| Setting | SwiftPM () | Xcode () |
|---|---|---|
| Language mode | or ( is not a reliable proxy) | Swift Language Version |
| Strict concurrency | | |
| Default isolation | | |
| Upcoming features | | |
If any of these are unknown, ask the developer to confirm them before giving migration-sensitive guidance. Do not guess.
Guardrails:
- Do not recommend
as a blanket fix. Justify why the code is truly UI-bound.@MainActor - Prefer structured concurrency over unstructured tasks. Use
only with a clear reason.Task.detached - If recommending
,@preconcurrency
, or@unchecked Sendable
, require a documented safety invariant and a follow-up removal plan.nonisolated(unsafe) - Optimize for the smallest safe change. Do not refactor unrelated architecture during migration.
- Course references are for deeper learning only. Use them sparingly and only when they clearly help answer the developer's question.
Quick Fix Mode
Use Quick Fix Mode when all of these are true:
- The issue is localized to one file or one type.
- The isolation boundary is clear.
- The fix can be explained in 1-2 behavior-preserving steps.
Skip Quick Fix Mode when any of these are true:
- Build settings or default isolation are unknown.
- The issue crosses module boundaries or changes public API behavior.
- The likely fix depends on unsafe escape hatches.
Common Diagnostics
| Diagnostic | First check | Smallest safe fix | Escalate to |
|---|---|---|---|
| Is this truly UI-bound? | Isolate the caller to or use only when main-actor ownership is correct. | , |
| Must the requirement run on the actor? | Prefer isolated conformance (e.g., ); use only for truly nonisolated requirements. | |
| What isolation boundary is being crossed? | Keep access inside one actor, or convert the transferred value to an immutable/value type. | , |
| Is actually required by protocol, override, or ? | Remove , or use a narrow suppression with rationale. Never add fake awaits. | |
| Is this legacy XCTest async waiting? | Replace with or Swift Testing equivalents. | |
| Core Data concurrency warnings | Are instances crossing contexts or actors? | Pass or map to a Sendable value type. | |
unavailable from asynchronous contexts | Are you debugging by thread instead of isolation? | Reason in terms of isolation and use Instruments/debugger instead. | |
| SwiftLint concurrency-related warnings | Which specific lint rule triggered? | Use for rule intent and preferred fixes; avoid dummy awaits. | |
When Quick Fixes Fail
- Gather project settings if not already confirmed.
- Re-evaluate which isolation boundaries the type crosses.
- Route to the matching reference file for a deeper fix.
- If the fix may change behavior, document the invariant and add verification steps.
Smallest Safe Fixes
Prefer changes that preserve behavior while satisfying data-race safety:
- UI-bound state: isolate the type or member to
.@MainActor - Shared mutable state: move it behind an
, or useactor
only if the state is UI-owned.@MainActor - Background work: when work must hop off caller isolation, use an
API markedasync
; when work can safely inherit caller isolation, use@concurrent
withoutnonisolated
. If a task mostly waits or retries before one UI-bound mutation, keep the delay off@concurrent
and hop back only for the final update.@MainActor - Sendability issues: prefer immutable values and explicit boundaries over
.@unchecked Sendable
Concurrency Tool Selection
| Need | Tool | Key Guidance |
|---|---|---|
| Single async operation | | Default choice for sequential async work |
| Fixed parallel operations | | Known count at compile time; auto-cancelled on throw |
| Dynamic parallel operations | | Unknown count; structured — cancels children on scope exit |
| Sync → async bridge | | Inherits actor context; use only with documented reason |
| Shared mutable state | | Prefer over locks/queues; keep isolated sections small |
| UI-bound state | | Only for truly UI-related code; justify isolation |
Common Scenarios
Network request with UI update
Task { @concurrent in let data = try await fetchData() await MainActor.run { self.updateUI(with: data) } }
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) } }
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
Migration Validation Loop
Apply this cycle for each migration change:
- Build — Run
or Xcode build to surface new diagnosticsswift build - Fix — Address one category of error at a time (e.g., all Sendable issues first)
- Rebuild — Confirm the fix compiles cleanly before moving on
- Test — Run the test suite to catch regressions (
or Cmd+U)swift test - Only proceed to the next file/module when all diagnostics are resolved
If a fix introduces new warnings, resolve them before continuing. Never batch multiple unrelated fixes — keep commits small and reviewable.
For detailed migration steps, see
references/migration.md.
Reference Router
Open the smallest reference that matches the question:
- Foundations
— async/await syntax, execution order, async let, URLSession patternsreferences/async-await-basics.md
— Task lifecycle, cancellation, priorities, task groups, structured vs unstructuredreferences/tasks.md
— Actor isolation, @MainActor, global actors, reentrancy, custom executors, Mutexreferences/actors.md
— Sendable conformance, value/reference types, @unchecked, region isolationreferences/sendable.md
— Execution model, suspension points, Swift 6.2 isolation behaviorreferences/threading.md
- Streams
— AsyncSequence, AsyncStream, when to use vs regular async methodsreferences/async-sequences.md
— Debounce, throttle, merge, combineLatest, channels, timersreferences/async-algorithms.md
- Applied topics
— Swift Testing first, XCTest fallback, leak checksreferences/testing.md
— Profiling with Instruments, reducing suspension points, execution strategiesreferences/performance.md
— Retain cycles in tasks, memory safety patternsreferences/memory-management.md
— NSManagedObject sendability, custom executors, isolation conflictsreferences/core-data.md
- Migration and tooling
— Swift 6 migration strategy, closure-to-async conversion, @preconcurrency, FRP migrationreferences/migration.md
— Concurrency-focused lint rules and SwiftLintreferences/linting.mdasync_without_await
- Glossary
— Quick definitions of core concurrency termsreferences/glossary.md
Verification Checklist
When changing concurrency code:
- Re-check build settings before interpreting diagnostics.
- Build and clear one category of errors before moving on. Do not batch unrelated fixes into the same change.
- Run tests, especially actor-, lifetime-, and cancellation-sensitive tests.
- Use Instruments for performance claims instead of guessing.
- Verify deallocation and cancellation behavior for long-lived tasks.
- Check
in long-running operations.Task.isCancelled - Never use semaphores or ad hoc locking in async contexts when actor isolation or
would express ownership more safely.Mutex
Note: This skill is based on the comprehensive Swift Concurrency Course by Antoine van der Lee.