swift-concurrency
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, (8) concurrency-related linter warnings (SwiftLint or similar; e.g. async_without_await, Sendable/actor isolation/MainActor lint).
Best use case
swift-concurrency is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
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, (8) concurrency-related linter warnings (SwiftLint or similar; e.g. async_without_await, Sendable/actor isolation/MainActor lint).
Teams using swift-concurrency should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/swift-concurrency/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How swift-concurrency Compares
| Feature / Agent | swift-concurrency | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
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, (8) concurrency-related linter warnings (SwiftLint or similar; e.g. async_without_await, Sendable/actor isolation/MainActor lint).
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
SKILL.md Source
# 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)
1. 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.
2. Before proposing fixes, identify the isolation boundary: `@MainActor`, custom actor, actor instance isolation, or nonisolated.
3. Do not recommend `@MainActor` as a blanket fix. Justify why main-actor isolation is correct for the code.
4. Prefer structured concurrency (child tasks, task groups) over unstructured tasks. Use `Task.detached` only with a clear reason.
5. If recommending `@preconcurrency`, `@unchecked Sendable`, or `nonisolated(unsafe)`, require:
- a documented safety invariant
- a follow-up ticket to remove or migrate it
6. For migration work, optimize for minimal blast radius (small, reviewable changes) and add verification steps.
7. Course references are for deeper learning only. Use them sparingly and only when they clearly help answer the developer's question.
## Recommended Tools for Analysis
When analyzing Swift projects for concurrency issues:
1. **Project Settings Discovery**
- Use `Read` on `Package.swift` for SwiftPM settings (tools version, strict concurrency flags, upcoming features)
- Use `Grep` for `SWIFT_STRICT_CONCURRENCY` or `SWIFT_DEFAULT_ACTOR_ISOLATION` in `.pbxproj` files
- Use `Grep` for `SWIFT_UPCOMING_FEATURE_` to find enabled upcoming features
## Project Settings Intake (Evaluate Before Advising)
Concurrency behavior depends on build settings. Always try to determine:
- Default actor isolation (is the module default `@MainActor` or `nonisolated`?)
- 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 `Package.swift` for `.defaultIsolation(MainActor.self)`.
- Check `Package.swift` 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 `project.pbxproj` for:
- `SWIFT_DEFAULT_ACTOR_ISOLATION`
- `SWIFT_STRICT_CONCURRENCY`
- `SWIFT_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.
## Quick Decision Tree
When a developer needs concurrency guidance, follow this decision tree:
1. **Starting fresh with async code?**
- Read `references/async-await-basics.md` for foundational patterns
- For parallel operations → `references/tasks.md` (async let, task groups)
2. **Protecting shared mutable state?**
- Need to protect class-based state → `references/actors.md` (actors, @MainActor)
- Need thread-safe value passing → `references/sendable.md` (Sendable conformance)
3. **Managing async operations?**
- Structured async work → `references/tasks.md` (Task, child tasks, cancellation)
- Streaming data → `references/async-sequences.md` (AsyncSequence, AsyncStream)
4. **Working with legacy frameworks?**
- Core Data integration → `references/core-data.md`
- General migration → `references/migration.md`
5. **Performance or debugging issues?**
- Slow async code → `references/performance.md` (profiling, suspension points)
- Testing concerns → `references/testing.md` (XCTest, Swift Testing)
6. **Understanding threading behavior?**
- Read `references/threading.md` for thread/task relationship and isolation
7. **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 `references/linting.md` for rule intent and preferred fixes; avoid dummy awaits as “fixes”.
- SwiftLint `async_without_await` warning
- Remove `async` if not required; if required by protocol/override/@concurrent, prefer narrow suppression over adding fake awaits. See `references/linting.md`.
- "Sending value of non-Sendable type ... risks causing data races"
- First: identify where the value crosses an isolation boundary
- Then: use `references/sendable.md` and `references/threading.md` (especially Swift 6.2 behavior changes)
- "Main actor-isolated ... cannot be used from a nonisolated context"
- First: decide if it truly belongs on `@MainActor`
- Then: use `references/actors.md` (global actors, `nonisolated`, isolated parameters) and `references/threading.md` (default isolation)
- "Class property 'current' is unavailable from asynchronous contexts" (Thread APIs)
- Use `references/threading.md` to avoid thread-centric debugging and rely on isolation + Instruments
- XCTest async errors like "wait(...) is unavailable from asynchronous contexts"
- Use `references/testing.md` (`await fulfillment(of:)` and Swift Testing patterns)
- Core Data concurrency warnings/errors
- Use `references/core-data.md` (DAO/`NSManagedObjectID`, 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 `references/migration.md`.
## Reference Files
Load these files as needed for specific topics:
- **`async-await-basics.md`** - async/await syntax, execution order, async let, URLSession patterns
- **`tasks.md`** - Task lifecycle, cancellation, priorities, task groups, structured vs unstructured
- **`threading.md`** - Thread/task relationship, suspension points, isolation domains, nonisolated
- **`memory-management.md`** - Retain cycles in tasks, memory safety patterns
- **`actors.md`** - Actor isolation, @MainActor, global actors, reentrancy, custom executors, Mutex
- **`sendable.md`** - Sendable conformance, value/reference types, @unchecked, region isolation
- **`linting.md`** - Concurrency-focused lint rules and SwiftLint `async_without_await`
- **`async-sequences.md`** - AsyncSequence, AsyncStream, when to use vs regular async methods
- **`core-data.md`** - NSManagedObject sendability, custom executors, isolation conflicts
- **`performance.md`** - Profiling with Instruments, reducing suspension points, execution strategies
- **`testing.md`** - XCTest async patterns, Swift Testing, concurrency testing utilities
- **`migration.md`** - Swift 6 migration strategy, closure-to-async conversion, @preconcurrency, FRP migration
## Best Practices Summary
1. **Prefer structured concurrency** - Use task groups over unstructured tasks when possible
2. **Minimize suspension points** - Keep actor-isolated sections small to reduce context switches
3. **Use @MainActor judiciously** - Only for truly UI-related code
4. **Make types Sendable** - Enable safe concurrent access by conforming to Sendable
5. **Handle cancellation** - Check Task.isCancelled in long-running operations
6. **Avoid blocking** - Never use semaphores or locks in async contexts
7. **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 `references/testing.md`).
- If performance-related, verify with Instruments (see `references/performance.md`).
- If lifetime-related, verify deinit/cancellation behavior (see `references/memory-management.md`).
## Glossary
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](https://www.swiftconcurrencycourse.com?utm_source=github&utm_medium=agent-skill&utm_campaign=skill-footer) by Antoine van der Lee.
## Technique Map
- **Project settings intake first** — Check Package.swift, pbxproj for isolation, strict concurrency, upcoming features; because advice depends on Swift 5 vs 6, targeted vs complete.
- **Identify isolation boundary** — @MainActor, custom actor, nonisolated; because fix depends on correct boundary.
- **Structured over unstructured** — Task groups, async let over Task.detached; because structured concurrency enables cancellation and clarity.
- **Triage-first playbook** — Map error message to reference (sendable, actors, threading, etc.); because common errors have known fixes.
- **Justify @MainActor** — Don't blanket fix; because overuse constrains parallelism.
- **Document safety invariants** — For @preconcurrency, @unchecked Sendable; because escape hatches need audit trail.
## Technique Notes
References: async-await-basics, tasks, actors, sendable, threading, migration, core-data, performance, testing. Swift 6 = strict by default. Use references sparingly; only when clearly helpful.
---
## Prompt Architect Overlay
**Role Definition:** Swift Concurrency expert. Best practices for async/await, actors, tasks, Sendable, Swift 6 migration. Thread safety, data race prevention, structured concurrency.
**Input Contract:** Accepts concurrency question, error message, migration request, or "use Swift Concurrency." Code snippet or project path. May include SwiftLint warnings.
**Output Contract:** Analysis with isolation boundary identified. Triage to appropriate reference. Code fix with justification. Migration steps if applicable. Verification checklist. Build settings noted when relevant.
**Edge Cases & Fallbacks:** If settings unknown→ask developer to confirm before migration advice. If Core Data→reference core-data.md. If @preconcurrency needed→require documented invariant + follow-up ticket. If legacy closures→migration.md for conversion.Related Skills
swift-human-guidelines
Comprehensive Swift 6 and SwiftUI development guidelines for building iOS 26, iOS 18, iPadOS, macOS, watchOS, visionOS, and tvOS applications. Covers Foundation Models API, BGContinuedProcessingTask, Call Translation API, Liquid Glass design system, data-race safety, typed throws, synchronization primitives, SwiftUI/UIKit interoperability, zoom transitions, and document-based apps. Use when building new Apple platform apps, implementing Apple Intelligence features, optimizing performance with Swift 6 concurrency, following Apple Human Interface Guidelines, creating cross-platform applications, or working with iOS 26/18 APIs. Triggers on Swift code, SwiftUI views, Xcode projects, app architecture, background processing, translation features, Foundation Models, synchronization, actors, Sendable types, or modern Apple platform development.
swift-conventions
Swift coding conventions and best practices for modern Swift development. Use when writing, reviewing, or refactoring Swift code to ensure consistency with naming conventions, access control, async/await patterns, and SwiftUI/framework best practices.
moai-lang-swift
Swift 6.0 enterprise development with async/await, SwiftUI, Combine, and Swift Concurrency. Advanced patterns for iOS, macOS, server-side Swift, and enterprise mobile applications with Context7 MCP integration.
go-concurrency-patterns
Master Go concurrency with goroutines, channels, sync primitives, and context. Use when building concurrent Go applications, implementing worker pools, or debugging race conditions.
axiom-swiftui-nav-diag
Use when debugging navigation not responding, unexpected pops, deep links showing wrong screen, state lost on tab switch or background, crashes in navigationDestination, or any SwiftUI navigation failure - systematic diagnostics with production crisis defense
asyncio-concurrency-patterns
Complete guide for asyncio concurrency patterns including event loops, coroutines, tasks, futures, async context managers, and performance optimization
125-java-concurrency
Use when you need to apply Java concurrency best practices — including thread safety fundamentals, ExecutorService thread pool management, concurrent design patterns like Producer-Consumer, asynchronous programming with CompletableFuture, immutability and safe publication, deadlock avoidance, virtual threads and structured concurrency, scoped values, backpressure, cancellation discipline, and observability for concurrent systems. Part of the skills-for-java project
swiftui-expert-skill
Write, review, or improve SwiftUI code following best practices for state management, view composition, performance, modern APIs, Swift concurrency, and iOS 26+ Liquid Glass adoption. Use when buil...
swiftui-components
SwiftUI component expert for building reusable views, custom modifiers, view compositions, and Liquid Glass integration. Use when creating new SwiftUI views, refactoring UI code, applying design tokens, or building production-ready component libraries for macOS Tahoe (26) and iOS 26.
swift-api-design-guidelines-skill
Write, review, or improve Swift APIs using Swift API Design Guidelines for naming, argument labels, documentation comments, terminology, and general conventions. Use when designing new APIs, refactoring existing interfaces, or reviewing API clarity and fluency.
axiom-swiftui-debugging
Use when debugging SwiftUI view updates, preview crashes, or layout issues - diagnostic decision trees to identify root causes quickly and avoid misdiagnosis under pressure
swift-actor-persistence
Use when building a thread-safe data persistence layer in Swift using actors with in-memory cache and file storage.