Skip to main content
skill CX Codex

swift-concurrency · jamesrochabrun — Claude Code skill: setup

A skill for building, reviewing, and refactoring Swift concurrency code. Use it for async/await, actors, isolation, and Swift 6+ migrations.

MIT 151 installs ★ 236 updated 2026-01-14

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add jamesrochabrun/skills --skill swift-concurrency -a claude-code
Open on GitHub

What swift-concurrency does

This skill covers three work modes: writing new asynchronous Swift code, auditing an existing codebase, and moving legacy patterns to Swift 6+. It guides isolation choices with @MainActor, custom actors, and nonisolated, then shows how to design async functions and run parallel work with async let or TaskGroup.

The SwiftUI section covers .task, inherited isolation, and task cancellation. Review checks include blocking waits, data races, Sendable violations, unnecessary actors, unstructured tasks, and missing cancellation checks. Refactoring guidance maps callbacks to async/await, DispatchQueue protection to actors, and Combine publishers to AsyncSequence.

The material targets Swift 6+ and includes Approachable Concurrency settings for Xcode 26+. A long-running operation that skips Task.isCancelled will not handle cancellation. Install the skill file in the Claude Code directory shown below.

What it helps with

  • design an async function with explicit isolation
  • audit code for data races and Sendable issues
  • convert callback APIs to async/await
  • replace DispatchQueue state protection with an actor
  • organize parallel work with async let or TaskGroup

Example prompts for the agent

  • Audit this Swift code for data races, Sendable issues, and blocking waits.
  • Convert the user-loading callback to async/await with a throwing continuation.
  • Design parallel image loading with async let and explain the isolation choice.

How to install swift-concurrency

1Skills CLI (Vercel)

npx skills add jamesrochabrun/skills --skill swift-concurrency -a claude-code

2Manually: put the files in place

~/.claude/skills/swift-concurrency/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/swift-concurrency/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about swift-concurrency

How do I install swift-concurrency in Claude Code?

Run npx skills add jamesrochabrun/skills --skill swift-concurrency -a claude-code. The skill file will be at ~/.claude/skills/swift-concurrency/SKILL.md.

What does swift-concurrency do?

It guides Swift development, reviews, and refactors around async/await, actors, MainActor, Sendable, isolation, and structured concurrency.

Which Swift and Xcode versions does it cover?

The guide targets Swift 6+ and includes Approachable Concurrency settings for Xcode 26+.

Source text

SKILL.md · MIT
---
name: swift-concurrency
description: Guide for building, auditing, and refactoring Swift code using modern concurrency patterns (Swift 6+). This skill should be used when working with async/await, Tasks, actors, MainActor, Sendable types, isolation domains, or when migrating legacy callback/Combine code to structured concurrency. Covers Approachable Concurrency settings, isolated parameters, and common pitfalls.
---

# Swift Concurrency

## Overview

This skill provides guidance for writing thread-safe Swift code using modern concurrency patterns. It covers three main workflows: building new async code, auditing existing code for issues, and refactoring legacy patterns to Swift 6+.

**Core principle**: Isolation is inherited by default. With Approachable Concurrency, code starts on MainActor and propagates through the program automatically. Opt out explicitly when needed.

## Workflow Decision Tree

```
What are you doing?
│
├─► BUILDING new async code
│   └─► See "Building Workflow" below
│
├─► AUDITING existing code
│   └─► See "Auditing Checklist" below
│
└─► REFACTORING legacy code
    └─► See "Refactoring Workflow" below
```

## Building Workflow

When writing new async code, follow this decision process:

### Step 1: Determine Isolation Needs

```
Does this type manage UI state or interact with UI?
│
├─► YES → Mark with @MainActor
│
└─► NO → Does it have mutable state shared across contexts?
         │
         ├─► YES → Consider: Can it live on MainActor anyway?
         │         │
         │         ├─► YES → Use @MainActor (simpler)
         │         │
         │         └─► NO → Use a custom actor (requires justification)
         │
         └─► NO → Leave non-isolated (default with Approachable Concurrency)
```

### Step 2: Design Async Functions

```swift
// PREFER: Inherit caller's isolation (works everywhere)
func fetchData(isolation: isolated (any Actor)? = #isolation) async throws -> Data {
  // Runs on whatever actor the caller is on
}

// USE WHEN: CPU-intensive work that must run in background
@concurrent
func processLargeFile() async -> Result { }

// AVOID: Non-isolated async without explicit choice
func ambiguousAsync() async { } // Where does this run?
```

### Step 3: Handle Parallel Work

```swift
// For known number of independent operations
async let avatar = fetchImage("avatar.jpg")
async let banner = fetchImage("banner.jpg")
let (a, b) = await (avatar, banner)

// For dynamic number of operations
try await withThrowingTaskGroup(of: Void.self) { group in
  for id in userIDs {
    group.addTask { try await fetchUser(id) }
  }
  try await group.waitForAll()
}
```

### Step 4: SwiftUI Integration

```swift
struct ProfileView: View {
  @State private var avatar: Image?

  var body: some View {
    avatar
      .task { avatar = await downloadAvatar() }  // Auto-cancels on disappear
      .task(id: userID) { /* Reloads when userID changes */ }
  }
}

// For user actions
Button("Save") {
  Task { await saveProfile() }  // Inherits MainActor isolation
}
```

## Auditing Checklist

When reviewing Swift concurrency code, check for these issues:

### Critical Issues (Must Fix)

- [ ] **Blocking the cooperative pool**: Look for `DispatchSemaphore.wait()`, `DispatchGroup.wait()`, or similar blocking calls inside async contexts
- [ ] **Data races**: Non-Sendable types crossing isolation boundaries without proper handling
- [ ] **Non-isolated async in non-Sendable types**: These only work from non-isolated contexts

### Common Issues (Should Fix)

- [ ] **Actor overuse**: Custom actors without justification (see "Actor Justification Test" in references)
- [ ] **Unnecessary `MainActor.run`**: Should usually be `@MainActor` on the function instead
- [ ] **Thinking async = background**: Synchronous CPU work inside async functions still blocks
- [ ] **Unstructured Tasks where structured works**: `Task { }` instead of `async let` or `TaskGroup`
- [ ] **Missing cancellation handling**: Long operations should check `Task.isCancelled`

### SwiftUI-Specific

- [ ] **Views not MainActor-isolated**: SwiftUI views should be `@MainActor` (or use `@Observable`)
- [ ] **Accessing @State from detached tasks**: Must hop back to MainActor

### Sendable Compliance

- [ ] **@unchecked Sendable overuse**: Should be rare and justified
- [ ] **Making everything Sendable**: Not all types need to cross boundaries
- [ ] **Non-Sendable closures escaping**: Check closure captures

## Refactoring Workflow

### From Callbacks to async/await

```swift
// BEFORE: Callback-based
func fetchUser(id: Int, completion: @escaping (Result<User, Error>) -> Void) {
  URLSession.shared.dataTask(with: url) { data, _, error in
    if let error { completion(.failure(error)); return }
    // ...
  }.resume()
}

// AFTER: async/await with continuation
func fetchUser(id: Int) async throws -> User {
  try await withCheckedThrowingContinuation { continuation in
    fetchUser(id: id) { result in
      continuation.resume(with: result)
    }
  }
}
```

### From DispatchQueue to Actors

```swift
// BEFORE: Queue-based protection
class BankAccount {
  private let queue = DispatchQueue(label: "account")
  private var _balance: Double = 0

  var balance: Double {
    queue.sync { _balance }
  }

  func deposit(_ amount: Double) {
    queue.async { self._balance += amount }
  }
}

// AFTER: Actor (if truly needs own isolation)
actor BankAccount {
  var balance: Double = 0

  func deposit(_ amount: Double) {
    balance += amount
  }
}

// BETTER: MainActor class (if doesn't need concurrent access)
@MainActor
class BankAccount {
  var balance: Double = 0

  func deposit(_ amount: Double) {
    balance += amount
  }
}
```

### From Combine to AsyncSequence

```swift
// BEFORE: Combine publisher
cancellable = NotificationCenter.default
  .publisher(for: .userDidLogin)
  .sink { notification in /* ... */ }

// AFTER: AsyncSequence
for await _ in NotificationCenter.default.notifications(named: .userDidLogin) {
  // Handle notification
}
```

## Quick Reference

| Keyword | Purpose |
|---------|---------|
| `async` | Function can suspend |
| `await` | Suspension point |
| `Task { }` | Start async work, inherits isolation |
| `Task.detached { }` | Start async work, no inheritance |
| `@MainActor` | Runs on main thread |
| `actor` | Type with isolated mutable state |
| `nonisolated` | Opts out of actor isolation |
| `nonisolated(nonsending)` | Inherits caller's isolation |
| `@concurrent` | Always run on background (Swift 6.2+) |
| `Sendable` | Safe to cross isolation boundaries |
| `sending` | One-way transfer of non-Sendable |
| `async let` | Start parallel work |
| `TaskGroup` | Dynamic parallel work |

## Approachable Concurrency Settings (Swift 6.2+)

For new Xcode 26+ projects, these are enabled by default:

```
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor
SWIFT_APPROACHABLE_CONCURRENCY = YES
```

Effects:
- Everything runs on MainActor unless explicitly marked otherwise
- `nonisolated async` functions stay on caller's actor instead of hopping to background
- Sendable errors become much rarer

## Resources

For detailed technical reference, consult:

- `references/fundamentals.md` - async/await, Tasks, structured concurrency
- `references/isolation.md` - Actors, MainActor, isolation domains, inheritance
- `references/sendable.md` - Sendable protocol, non-Sendable patterns, isolated parameters
- `references/common-mistakes.md` - Detailed examples of what to avoid
- `references/glossary.md` - Complete terminology reference

**Search patterns for references:**
- Isolation: `grep -i "isolation\|actor\|mainactor\|nonisolated"`
- Sendable: `grep -i "sendable\|sending\|boundary"`
- Tasks: `grep -i "task\|taskgroup\|async let\|structured"`

© jamesrochabrun · MIT · jamesrochabrun/skills

Similar skills

All skills for Programming languages →

swift-concurrency by other authors comes first.

swift-concurrency AvdLee swift-concurrency is a Claude Code skill that diagnoses Swift Concurrency issues and suggests safe fixes. It activates for Swift 6 migration and work involving tasks, actors, or Sendable. CX Codex +1 17,700installs swift-concurrency dpearson2699 swift-concurrency fixes Sendable errors and actor isolation diagnostics in Swift 6.2+ while adopting approachable concurrency features. CX Codex +1 4,600installs swift-concurrency Prisma-Labs-Dev A reference skill for Swift Concurrency: async/await, Task, TaskGroup, actors, AsyncSequence and continuation bridges. Useful when the agent writes async Swift code. CX Codex +1 752installs swift-concurrency wendylabsinc swift-concurrency guides your coding assistant through async/await, actor boundaries, and Swift 6 strict concurrency checks without careless @MainActor escapes. CX Codex +1 ★ 64repo stars guide-swift-concurrency Prisma-Labs-Dev guide-swift-concurrency guides AI agents through reviewing and writing concurrent Swift 6.2 code under strict concurrency checks. It flags actor reentrancy bugs, unsafe tasks, and GCD patterns. CX Codex +1 539installs swift-expert https://github.com/Jeffallan swift-expert — a Swift skill that walks the agent through architecture, SwiftUI state, async/await and actors, with build checks in between. Built for iOS and macOS work. CX Codex +1 4,500installs axiom-concurrency CharlesWiltgen axiom-concurrency — a skill for concurrency work in Apple-platform apps: actors, @MainActor, Sendable, data races, async/await patterns. CX Codex +1 1,400installs swift-concurrency-pro Paul Hudson swift-concurrency-pro reviews Swift code for concurrency correctness, modern API usage and common async/await pitfalls. Useful when reading or reviewing async code. CX Codex +1 13,100installs migrating-to-swift-concurrency kylehughes migrating-to-swift-concurrency supplies Apple's Swift Concurrency Migration Guide to your agent. Helps resolve data races, fix Sendable errors, and switch to Swift 6. CX Codex +1 ★ 58repo stars swift-concurrency-expert Dimillian swift-concurrency-expert is a Claude Code skill for reviewing and fixing concurrency issues in Swift 6.2+, including Sendable, actor isolation, and migrating completion handlers to async/await. CX Codex +1 2,100installs

From the same set23

The whole set →
openai-prompt-engineer The openai-prompt-engineer skill helps draft and refine prompts for GPT-5 and other language models. Use it to shape instructions, choose a prompting method, and specify the response format. CX Codex +1 211installs releasing-macos-apps The releasing-macos-apps skill guides macOS app releases from version changes and code signing through DMG creation, Apple notarization, and Sparkle updates. CX Codex +1 210installs content-brief-generator The content-brief-generator skill builds structured briefs for articles, docs, landing pages, and other formats. Use it when a writer needs a clear audience, goal, outline, and SEO direction. CX Codex +1 207installs design-brief-generator design-brief-generator is a Claude Code skill that builds structured design briefs. It activates for requests about project requirements, goals, and design planning. CX Codex +1 181installs llm-router llm-router routes requests to OpenAI, Grok, Groq, DeepSeek or OpenRouter via SwiftOpenAI-CLI. Runs in agent mode, supports model selection and MCP tools. CX Codex +1 149installs engineer-expertise-extractor engineer-expertise-extractor — a skill that extracts an engineer's coding style, patterns, and best practices from GitHub contributions, building a structured knowledge base to replicate their expertise across a team. CX Codex +1 144installs technical-launch-planner technical-launch-planner is a Claude Code skill that plans technical product launches by assessing scope, building a work plan, and checking team and materials readiness. CX Codex +1 137installs engineer-skill-creator engineer-skill-creator builds a structured skill from an engineer profile, with focused lookups for tasks, languages, and patterns. Use it when an agent needs a developer’s specific coding approach. CX Codex +1 137installs

Project sponsors

Companies that keep this analytics open