/ios-agent-skills:swift-concurrencyfrom ios-agent-skills
Resolves Swift Concurrency issues on Apple platforms: actor reentrancy, AsyncStream lifecycle, TaskGroup throttling, Sendable conformance, Swift 6 migration, and strict concurrency errors.
Ships in ios-agent-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Enterprise-grade skill for Swift Concurrency crash prevention, strict concurrency migration, and Swift 6.2 readiness. Opinionated: prescribes structured concurrency over unstructured, actors for shared mutable state, @MainActor for UI isolation, Mutex for synchronous critical sections, compile-time isolation over runtime hops, and withCheckedContinuation over withUnsafeContinuation. Every rule in this skill has broken a real production app.
Application Layer -> Structured concurrency: TaskGroup, async let, .task modifier
Actor Layer -> actor for shared mutable state, @MainActor for UI state
Async/Await Layer -> Cooperative, non-blocking async functions on the cooperative pool
Sendable Layer -> Compile-time data-race safety at isolation boundary crossings
Compiler Layer -> SWIFT_STRICT_CONCURRENCY=complete, Swift 6 language mode, TSan
Does this type own mutable state shared across concurrency domains?
+-- YES -> Does it need to update UI?
| +-- YES -> @MainActor class/struct
| +-- NO -> Is the state complex or involves await points?
| +-- YES -> actor
| +-- NO -> Mutex<State> (Swift 6+, iOS 18+) or NSLock wrapper
+-- NO -> Is it a value type with only Sendable stored properties?
+-- YES -> Implicitly Sendable (internal types only; public needs explicit conformance)
+-- NO -> Can it be redesigned as a value type?
+-- YES -> Refactor to struct/enum
+-- NO -> Keep non-Sendable, contain within single isolation domain
How many concurrent operations?
+-- Known at compile time (2-5) -> async let (simplest, heterogeneous return types OK)
+-- Dynamic count (N items) -> TaskGroup
| +-- Need results?
| | +-- YES -> withThrowingTaskGroup (iterate with for await)
| | +-- NO -> withDiscardingTaskGroup (no result accumulation leak)
| +-- Unbounded input? -> Throttle: limit addTask to activeProcessorCount
+-- Fire-and-forget from sync context?
+-- Need caller's isolation -> Task { } (inherits actor context)
+-- Need background, no isolation -> Task.detached { }
WARNING: detached strips priority, task-locals, cancellation propagation. Rarely correct.
Does the API block the current thread?
+-- YES (semaphore.wait, group.wait, Thread.sleep, sync file I/O, NSLock in long section)
| -> NEVER in async context. Deadlocks cooperative pool (capped at CPU core count).
| -> Wrap in DispatchQueue + withCheckedContinuation to move off cooperative pool.
+-- NO -> Is the work CPU-bound and takes >1ms?
+-- YES -> Use @concurrent func (Swift 6.2+) or nonisolated func on dedicated queue
+-- NO -> Safe in async context
When: First encounter with a codebase, or preparing for Swift 6 migration.
SWIFT_STRICT_CONCURRENCY setting (references/compiler-flags-ci.md)references/crash-patterns.md)@unchecked Sendable usage (references/sendable-transfer.md)references/actor-isolation.md)finish(), infinite sequences, no backpressure (references/asyncstream-memory.md)references/security-concurrency.md)refactoring/ directory with severity-ranked findings (references/refactoring-workflow.md)When: Enabling SWIFT_STRICT_CONCURRENCY=complete or Swift 6 mode.
The migration is a THREE-STEP progression, not a binary flip. Do not jump directly to complete or to Swift 6 language mode — you will drown in errors. The canonical progression is:
| Step | Setting | What it does |
|---|---|---|
| 1. Targeted | SWIFT_STRICT_CONCURRENCY=targeted | Surfaces warnings only in code explicitly marked Sendable or in @preconcurrency boundaries. Low-noise entry point. Ship this first, fix the surfaced warnings, then advance. |
| 2. Complete | SWIFT_STRICT_CONCURRENCY=complete | Enables all concurrency checks as warnings. Work through each module until the warning count is zero. Still compiles and ships while you migrate. |
| 3. Swift 6 language mode | SWIFT_VERSION=6.0 | Promotes all concurrency checks from warnings to errors. Only switch here AFTER the module is clean under complete. This is the final gate. |
Most teams spend weeks in step 2 before advancing to step 3. Enabling step 3 prematurely produces hundreds of errors with no actionable incremental path.
references/migration-strategy.md)references/migration-strategy.md)static var → actor, Mutex, or let (references/actor-isolation.md)sending where applicable (references/sendable-transfer.md)references/swift-6-2-changes.md)references/compiler-flags-ci.md)LIBDISPATCH_COOPERATIVE_POOL_STRICT=1 (references/testing-debugging.md)When: Building a new feature from scratch with Swift Concurrency.
references/sendable-transfer.md)references/advanced-patterns.md)references/testing-debugging.md)withMainSerialExecutor (references/testing-debugging.md)When: Crash report points to continuation, actor, AsyncStream, or TaskGroup.
references/crash-patterns.md)references/actor-isolation.md)references/security-concurrency.md)references/testing-debugging.md)LIBDISPATCH_COOPERATIVE_POOL_STRICT=1<critical_rules> Whether reviewing, generating, or refactoring concurrent code, every output must be data-race-free, deadlock-free, and production-ready under Swift 6 strict concurrency. ALWAYS:
semaphore.wait(), group.wait(), Thread.sleep(), synchronous file I/O in any async contextwithCheckedThrowingContinuationawait -- actors are reentrant at suspension pointswithDiscardingTaskGroup for fire-and-forget child tasks -- prevents result accumulation memory leaksonTermination for EVERY external resource cleanup — NotificationCenter observers, delegate assignments, timers, KVO, Combine subscribers, or any observer/callback registration made inside the stream's setup closure. deinit is not sufficient because an AsyncStream can outlive or be dropped independently of its owner; onTermination fires when the stream is finished or its task is cancelled, which is exactly when cleanup must run. Always pair every addObserver/delegate = self/registration call inside the stream setup with a symmetric removal in onTermination. Also call continuation.finish() from inside onTermination when your stream is an infinite observer patternSendable conformance -- no automatic inference across module boundariesProcessInfo.processInfo.activeProcessorCount@MainActor annotation for UI isolation, not MainActor.run {}CancellationError silently -- never surface "cancelled" to usersClock protocol for time-dependent code -- never hardcode Task.sleepnonisolated async now inherits caller's actor; use @concurrent for explicit background<thought> analyzing isolation domains, Sendable conformance, and potential reentrancy
</critical_rules><fallback_strategies> When fixing concurrency issues, you may encounter cascading compiler errors. If you fail to fix the same issue twice, break the loop:
@preconcurrency import for the offending module and log a migration task in refactoring/discovered.md. Why: @preconcurrency suppresses Sendable checking at module boundaries while preserving local safety — it's the sanctioned escape hatch, unlike @unchecked Sendable which bypasses all checking.@MainActor to a class cascades into dozens of async call-site errors. Start by marking individual methods @MainActor instead of the whole class. Why: class-level isolation propagates to all methods, forcing every call site to be async — method-level isolation limits the blast radius.addTask, release inside the task. Limit to ProcessInfo.processInfo.activeProcessorCount * 2. Why: each child task retains its result until the group iterates — unbounded tasks accumulate results in memory.
</fallback_strategies>Before finalizing generated or refactored concurrent code, verify ALL:
[] No cooperative pool blocking -- no semaphore.wait, Thread.sleep, sync I/O in any async function
[] No continuation leaks -- every withChecked*Continuation resumes on every path (success, failure, cancellation)
[] No unchecked Sendable -- every @unchecked Sendable has documented synchronization (Mutex, NSLock, or actor)
[] Actor reentrancy -- state re-checked after every await inside actors
[] AsyncStream cleanup -- finish() called in onTermination, no infinite sequence without cancellation
[] TaskGroup bounded -- child task count limited for unbounded input
[] MainActor correct -- UI state @MainActor-isolated, no MainActor.run anti-pattern
[] Swift 6.2 ready -- nonisolated async caller-isolation understood, @concurrent used where needed
[] Cancellation handled -- withTaskCancellationHandler for long-running ops, CancellationError caught silently
[] Tests deterministic -- Clock injected, withMainSerialExecutor used, no flaky timing dependencies
[] Compiler flags -- SWIFT_STRICT_CONCURRENCY=complete set, TSan enabled in CI
Start here for most tasks:
crash-patterns.md,actor-isolation.md,sendable-transfer.md. Then consult the specific reference based on your workflow.
| Reference | When to Read |
|---|---|
references/rules.md | Do's and Don'ts quick reference: priority rules and critical anti-patterns |
references/crash-patterns.md | Production crash patterns: continuation misuse, cooperative pool deadlocks, TaskGroup OOM, watchdog kills, release-only crashes |
references/actor-isolation.md | Task.init inherits isolation, compile-time isolation, nonisolated deinit, isolated deinit (Swift 6.1+), split isolation, assumeIsolated, actors as advanced tools |
references/sendable-transfer.md | sending keyword, region-based isolation, @unchecked Sendable risks, public type inference, @preconcurrency scope |
references/asyncstream-memory.md | Infinite sequence leaks, continuation.finish(), backpressure policies, withDiscardingTaskGroup, Task.detached stripping |
references/swift-6-2-changes.md | Approachable Concurrency: caller isolation, @concurrent, MainActor default, @preconcurrency runtime crashes |
references/migration-strategy.md | Bottom-up module migration, third-party SDK blockers, global singleton conversion, actor hopping overhead |
references/security-concurrency.md | Token refresh serialization, TOCTOU at await, Keychain serialization, sensitive data, actor double-spend |
references/compiler-flags-ci.md | SWIFT_STRICT_CONCURRENCY, SPM per-target flags, Swift 6.2 feature flags, SwiftLint rules, CI pipeline |
references/advanced-patterns.md | Mutex vs actors, async let vs TaskGroup, isolated parameters, withTaskCancellationHandler, .task modifier, task-locals |
references/diagnostics-fix-mapping.md | Compiler error → fix mapping: "Sending risks data races", "non-sendable capture", "static property not safe", isolation errors |
references/cancellation-patterns.md | Cooperative cancellation, withTaskCancellationHandler, CancellationError handling, timeout patterns, SwiftUI .task |
references/memory-retain-cycles.md | Task retain cycles, weak self patterns, async sequence retention, isolated deinit, testing for leaks |
references/core-data-concurrency.md | NSManagedObject not Sendable, DAO pattern, NSManagedObjectID, actor-isolated context, @MainActor conflicts |
references/testing-async.md | Swift Testing async, confirmation(), Clock injection, withMainSerialExecutor, TSan, deterministic tests |
references/testing-debugging.md | withMainSerialExecutor, Clock injection, TSan, Instruments, deterministic tests, timeouts |
references/refactoring-workflow.md | refactoring/ directory protocol, per-feature plans, severity ordering, PR sizing, verification checklist |
README.md (opens in a new tab)references/actor-isolation.md (opens in a new tab)references/advanced-patterns.md (opens in a new tab)references/asyncstream-memory.md (opens in a new tab)references/cancellation-patterns.md (opens in a new tab)references/compiler-flags-ci.md (opens in a new tab)references/core-data-concurrency.md (opens in a new tab)references/crash-patterns.md (opens in a new tab)references/diagnostics-fix-mapping.md (opens in a new tab)references/memory-retain-cycles.md (opens in a new tab)references/migration-strategy.md (opens in a new tab)references/refactoring-workflow.md (opens in a new tab)references/rules.md (opens in a new tab)references/security-concurrency.md (opens in a new tab)references/sendable-transfer.md (opens in a new tab)references/swift-6-2-changes.md (opens in a new tab)references/testing-async.md (opens in a new tab)references/testing-debugging.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
swift-concurrency, actors, async-await, sendable, swift-6-migration
Generated from the plugin's indexed repository (rusel95/ios-agent-skills) — no native marketplace selected
npx claudepluginhub p/rusel95-ios-agent-skills11 skills in this plugin
/gcd-operationsUse for iOS/macOS concurrency problems involving dispatch queues, locks, or thread safety. Triggers on: deadlocks (sync on main, nested sync, ABBA lock ordering), thread explosion from too many DispatchQueue.global() calls, data races flagged by Thread Sanitizer (TSan), DispatchGroup enter/leave imbalance, DispatchSource timer leaks, lock selection (NSLock vs OSAllocatedUnfairLock vs os_unfair_lock), reader-writer barriers, AsyncOperation subclasses, dispatchPrecondition usage, and OperationQueue throttling. Also use when migrating GCD patterns to Swift Concurrency actors. Apply whenever someone asks about thread-safe properties, concurrent access to shared state, or sees TSan warnings in Apple platform code — even if they don't say 'GCD' or 'concurrency.'/ios-accessibilityProduction-grade iOS accessibility skill covering VoiceOver, Dynamic Type, color contrast, motion, Switch Control, Voice Control, and WCAG 2.2 compliance for both SwiftUI and UIKit. This skill should be used when creating new iOS screens or views, reviewing existing iOS code for accessibility, adding VoiceOver support, fixing Dynamic Type issues, auditing WCAG compliance, implementing accessibilityLabel/traits/hints, grouping elements for assistive technology, adding custom actions or rotors, respecting system accessibility preferences (reduce motion, increase contrast, differentiate without color), writing accessibility-focused XCTest audits, or preparing apps for enterprise compliance (ADA, EAA, Section 508). Use this skill any time someone is working with iOS accessibility, VoiceOver, Dynamic Type, assistive technology, WCAG mapping, or accessibility modifiers in SwiftUI or UIKit — even if they only say 'make this accessible' or 'add VoiceOver support' or 'check contrast.' Also run an accessibility pass on any newly generated SwiftUI or UIKit view code before finalizing — AI coding assistants systematically produce inaccessible code by default (hardcoded fonts, onTapGesture instead of Button, missing labels, no system preference checks) and this skill corrects those patterns./ios-localizationProduction-grade iOS localization skill covering String Catalogs (.xcstrings), CLDR pluralization, SwiftUI/UIKit localization APIs, RTL layout, date/number/currency formatting, and enterprise patterns (modular apps, white-label, accessibility localization). This skill should be used when creating or editing localized iOS strings, working with .xcstrings or .strings files, implementing pluralization, formatting dates/numbers/currencies for display, building RTL-compatible layouts, localizing accessibility labels, setting up localization in Swift Packages, or reviewing code for localization correctness. Use this skill any time someone is working with iOS localization, i18n, l10n, String Catalogs, plural rules, RTL, date formatting, or translated strings — even if they only say 'add a string' or 'format this date' or 'make this work in Arabic.' Also audit any newly generated user-facing iOS code for localization failures before finalizing — AI coding assistants systematically produce broken localization (hardcoded strings, missing plural categories, wrong date formats, left/right instead of leading/trailing) and this skill corrects those patterns. For .xcstrings files that are too large for direct editing, use the bundled Python scripts in scripts/ to validate, add entries, audit completeness, and fix plural categories programmatically./ios-loggingEnterprise skill for iOS production error observability and logging (iOS 15+, Swift 5.5+). The trigger is OBSERVABILITY intent — the user wants errors captured and visible in production, not just handled. Use when: adding os.Logger or replacing print() with structured logging; setting up or integrating a crash SDK (Sentry, Crashlytics, PostHog); auditing error handling for silent failures (catch blocks with no Logger/ErrorReporter call, try? on network/auth/payment operations, Task {} with no do-catch, Combine .replaceError() killing error visibility); adding privacy annotations to logs; integrating MetricKit for OOM/hang detection; or asking why errors are disappearing silently in production. Also use when reviewing any catch block, try?, or Task {} specifically to ensure errors reach a remote crash reporting service — not just for writing error handling in general./ios-securityUse for any iOS security question — whether you're asking about a specific vulnerability, checking if a pattern is secure, or running a full audit. Triggers on: Keychain vs UserDefaults decisions, ATS/NSAllowsArbitraryLoads configuration, certificate pinning implementation, WebView security (UIWebView, WKWebView), hardcoded secrets or API keys, jailbreak/tamper detection, biometric authentication, MASVS controls, OWASP mobile security, App Store rejection risks, and compliance requirements (HIPAA, PCI DSS, GDPR). Also use when someone asks 'is this secure?', 'what should I use instead?', or 'how do I fix this?' about any iOS storage, network, or cryptography pattern./ios-testingInvoke any time a user is writing iOS/Swift tests or asking why tests behave a certain way — including XCTest versus Swift Testing (@Test/#expect) choices, async ViewModel tests with @Observable or @Published, snapshot testing across device sizes, mocking protocols for dependency injection, setUp/tearDown lifecycle issues, tests that fail on CI but pass locally, flaky async tests, testing VIPER/TCA/MVVM architectures, and coverage gaps on error paths. The trigger is user intent: they are trying to verify, assert, or validate iOS/Swift behavior in a test context, whether they use the word 'testing' or not.Other plugins' skills for the same job