jpskill.com
🛠️ 開発・MCP コミュニティ

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.

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o swift-concurrency.zip https://jpskill.com/download/17369.zip && unzip -o swift-concurrency.zip && rm swift-concurrency.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17369.zip -OutFile "$d\swift-concurrency.zip"; Expand-Archive "$d\swift-concurrency.zip" -DestinationPath $d -Force; ri "$d\swift-concurrency.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して swift-concurrency.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → swift-concurrency フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
13

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Swift Concurrency

概要

このスキルは、Swift Concurrencyに関する専門的なガイダンスを提供し、最新のasync/awaitパターン、アクター、タスク、Sendable準拠、およびSwift 6への移行を網羅します。このスキルを活用して、開発者が安全で高性能な並行コードを作成し、Swiftの構造化された並行処理モデルの複雑さを乗り越える手助けをします。

エージェントの行動規範 (以下のルールに従うこと)

  1. プロジェクト/パッケージファイルを分析して、アドバイスが依存する場合に、どのSwift言語モード(Swift 5.x vs Swift 6)およびどのXcode/Swiftツールチェーンが使用されているかを調べます。
  2. 修正を提案する前に、分離境界を特定します:@MainActor、カスタムアクター、アクターインスタンス分離、またはnonisolated
  3. @MainActorを包括的な修正として推奨しないでください。なぜメインアクター分離がそのコードに適しているのかを正当化してください。
  4. 非構造化タスクよりも構造化された並行処理(子タスク、タスクグループ)を優先します。Task.detachedは明確な理由がある場合にのみ使用してください。
  5. @preconcurrency@unchecked Sendable、またはnonisolated(unsafe)を推奨する場合は、以下を必須とします。
    • 文書化された安全性の不変条件
    • それを削除または移行するためのフォローアップチケット
  6. 移行作業では、最小限の爆発範囲(小さく、レビュー可能な変更)を最適化し、検証ステップを追加します。
  7. コースの参考文献は、より深い学習のためだけに使用します。それらを控えめに、そして開発者の質問に明確に答えるのに役立つ場合にのみ使用してください。

プロジェクト設定の取り込み (アドバイスする前に評価)

並行処理の動作はビルド設定に依存します。常に以下を判断するように努めてください。

  • デフォルトのアクター分離(モジュールのデフォルトは@MainActorですか、それともnonisolatedですか?)
  • 厳密な並行性チェックレベル(minimal/targeted/complete)
  • 今後の機能が有効になっているかどうか(特にNonisolatedNonsendingByDefault
  • Swift言語モード(Swift 5.x vs Swift 6)およびSwiftPMツールのバージョン

手動チェック (スクリプトなし)

  • SwiftPM:
    • Package.swift.defaultIsolation(MainActor.self)を確認します。
    • Package.swift.enableUpcomingFeature("NonisolatedNonsendingByDefault")を確認します。
    • 厳密な並行性フラグを確認します:.enableExperimentalFeature("StrictConcurrency=targeted")(または類似のもの)。
    • 上部のツールバージョンを確認します:// swift-tools-version: ...
  • Xcodeプロジェクト:
    • project.pbxprojで以下を検索します。
      • SWIFT_DEFAULT_ACTOR_ISOLATION
      • SWIFT_STRICT_CONCURRENCY
      • SWIFT_UPCOMING_FEATURE_(および/またはSWIFT_ENABLE_EXPERIMENTAL_FEATURES

これらのいずれかが不明な場合は、移行に影響するガイダンスを提供する前に、開発者に確認を求めてください。

クイック意思決定ツリー

開発者が並行処理のガイダンスを必要とする場合は、この意思決定ツリーに従ってください。

  1. asyncコードを新たに開始しますか?

    • 基本的なパターンについては、references/async-await-basics.mdを読んでください。
    • 並列操作の場合 → references/tasks.md (async let, task groups)
  2. 共有の可変状態を保護しますか?

    • クラスベースの状態を保護する必要があります → references/actors.md (actors, @MainActor)
    • スレッドセーフな値の受け渡しが必要です → references/sendable.md (Sendable conformance)
  3. async操作を管理しますか?

    • 構造化されたasync作業 → references/tasks.md (Task, child tasks, cancellation)
    • ストリーミングデータ → references/async-sequences.md (AsyncSequence, AsyncStream)
  4. レガシーフレームワークを使用していますか?

    • Core Dataの統合 → references/core-data.md
    • 一般的な移行 → references/migration.md
  5. パフォーマンスまたはデバッグの問題がありますか?

    • 遅いasyncコード → references/performance.md (profiling, suspension points)
    • テストに関する懸念 → references/testing.md (XCTest, Swift Testing)
  6. スレッドの動作を理解しますか?

    • スレッド/タスクの関係と分離については、references/threading.mdを読んでください。
  7. タスクに関するメモリの問題がありますか?

    • 保持サイクルの防止については、references/memory-management.mdを読んでください。

トリアージ優先プレイブック (一般的なエラー -> 次の最善の行動)

  • Sendableでない型の値を送信すると、データ競合が発生する可能性があります」
    • まず:値が分離境界を越える場所を特定します。
    • 次に:references/sendable.mdreferences/threading.mdを使用します(特にSwift 6.2の動作変更)。
  • 「メインアクター分離...は、非分離コンテキストから使用できません」
    • まず:それが本当に@MainActorに属するかどうかを判断します。
    • 次に:references/actors.md(グローバルアクター、nonisolated、分離されたパラメータ)とreferences/threading.md(デフォルトの分離)を使用します。
  • 「クラスプロパティ'current'は非同期コンテキストから利用できません」(Thread APIs)
    • references/threading.mdを使用して、スレッド中心のデバッグを避け、分離とInstrumentsに依存します。
  • 「wait(...)は非同期コンテキストから利用できません」のようなXCTest asyncエラー
    • references/testing.md (await fulfillment(of:)とSwift Testingパターン)を使用します。
  • Core Dataの並行性に関する警告/エラー
    • references/core-data.md (DAO/NSManagedObjectID、デフォルトの分離の競合)を使用します。

コアパターンリファレンス

各並行処理ツールの使用時期

async/await - 既存の同期コードを非同期にする

// 用途: 単一の非同期操作
func fetchUser() async throws -> User {
    try await networkClient.get("/user")
}

async let - 複数の独立した非同期操作を並行して実行する

// 用途: コンパイル時に既知の固定数の並列操作
async let user = fetchUser()
async let posts = fetchPosts()
let profile = try await (user, posts)

Task - 非構造化された非同期作業を開始する

// 用途: 実行しっぱなしの操作、同期コンテキストから非同期コンテキストへのブリッジ
Task {
    await updateUI()
}

Task Group - 構造化された並行処理による動的な並列操作

// 用途: コンパイル時に不明な数の並列操作
await withTaskGroup(of: Result.self) { group in
    for item in items {
        group.addTask { await process(item) }
    }
}

Actor - データ競合から可変状態を保護する

// 用途: 複数のコンテキストからアクセスされる共有の可変状態
actor DataCache {
    private var cache: [String: Data] = [:]
    func get(_ key: String) -> Data? { cache[ke
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

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.

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)

  • "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

// 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 = ""
}

Common Scenarios

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)
    }
}

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
  • 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 by Antoine van der Lee.

同梱ファイル

※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。