Communitygithub.com

Swift 6.2 親しみやすい並行性

Swift 6.2の並行性モデル(デフォルトでシングルスレッド、@concurrentによる明示的なバックグラウンドオフロード、メインアクター型の隔離準拠)を採用するためのパターン。データ競合エラーを排除しつつパフォーマンスを維持します。

Swift 6.2 親しみやすい並行性 とは?

このスキルは、Swift 6.2で導入された「親しみやすい並行性(Approachable Concurrency)」モデルを採用するための包括的なガイドです。従来のSwift 6.1以前では、async関数が暗黙的にバックグラウンドスレッドにオフロードされることで、一見安全なコードでもデータ競合が発生していました。Swift 6.2ではこれを根本的に修正し、async関数はデフォルトで呼び出し元のアクター上で実行されるため、データ競合を未然に防ぎます。主な機能として、@MainActor型がプロトコルに安全に準拠できる「隔離準拠(Isolated Conformances)」、グローバル変数や静的変数への@MainActor推論のデフォルト化、そして明示的な並行処理のための@concurrent属性を提供します。このスキルは、Xcode 26でビルド設定を有効にすることで利用可能で、Swift Package Managerでも設定できます。既存のSwift 5.x/6.0/6.1プロジェクトからの移行手順、ベストプラクティス、アンチパターンもカバーしており、データ競合をコンパイル時に検出しながら、安全で高パフォーマンスなコードを記述するための指針を提供します。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/swift-concurrency-6-2

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Swift 6.2 親しみやすい並行性 は何をしますか?

Swift 6.2の並行性モデルを採用するためのパターンです。このモデルでは、コードはデフォルトでシングルスレッドで実行され、並行性は明示的に導入されます。これにより、一般的なデータ競合エラーを排除しつつ、パフォーマンスを犠牲にすることはありません。

いつ活性化するか

  • Swift 5.xまたは6.0/6.1プロジェクトをSwift 6.2に移行する場合
  • データ競合安全に関するコンパイラエラーを解決する場合
  • MainActorベースのアプリケーションアーキテクチャを設計する場合
  • CPU負荷の高い処理をバックグラウンドスレッドにオフロードする場合
  • MainActor隔離型の型にプロトコル準拠を実装する場合
  • Xcode 26で「親しみやすい並行性」ビルド設定を有効にする場合

核となる問題: 暗黙的なバックグラウンドオフロード

Swift 6.1以前では、async関数が暗黙的にバックグラウンドスレッドにオフロードされる可能性があり、一見安全なコードでもデータ競合エラーが発生していました:

// Swift 6.1: エラー
@MainActor
final class StickerModel {
    let photoProcessor = PhotoProcessor()

    func extractSticker(_ item: PhotosPickerItem) async throws -> Sticker? {
        guard let data = try await item.loadTransferable(type: Data.self) else { return nil }

        // エラー: 'self.photoProcessor'を送信するとデータ競合が発生するリスクがあります
        return await photoProcessor.extractSticker(data: data, with: item.itemIdentifier)
    }
}

Swift 6.2ではこれを修正します: async関数はデフォルトで呼び出し元のアクター上に留まります。

// Swift 6.2: OK — asyncはMainActor上に留まり、データ競合は発生しません
@MainActor
final class StickerModel {
    let photoProcessor = PhotoProcessor()

    func extractSticker(_ item: PhotosPickerItem) async throws -> Sticker? {
        guard let data = try await item.loadTransferable(type: Data.self) else { return nil }
        return await photoProcessor.extractSticker(data: data, with: item.itemIdentifier)
    }
}

核となるパターン — 隔離準拠

MainActor型が、非隔離プロトコルに安全に準拠できるようになりました:

protocol Exportable {
    func export()
}

// Swift 6.1: エラー — メインアクター隔離コードに侵入します
// Swift 6.2: 隔離準拠によりOK
@MainActor extension StickerModel: Exportable {
    func export() {
        photoProcessor.exportAsPNG()
    }
}

コンパイラは、準拠がメインアクター上でのみ使用されることを保証します:

// OK — ImageExporterも@MainActorです
@MainActor
struct ImageExporter {
    var items: [any Exportable]

    mutating func add(_ item: StickerModel) {
        items.append(item)  // 安全: 同じアクター隔離
    }
}

// エラー — 非隔離コンテキストはMainActor準拠を使用できません
nonisolated struct ImageExporter {
    var items: [any Exportable]

    mutating func add(_ item: StickerModel) {
        items.append(item)  // エラー: MainActor隔離準拠はここでは使用できません
    }
}

核となるパターン — グローバル変数と静的変数

グローバル/静的状態をMainActorで保護します:

// Swift 6.1: エラー — non-Sendable型は共有可変状態を持つ可能性があります
final class StickerLibrary {
    static let shared: StickerLibrary = .init()  // エラー
}

// 修正: @MainActorで注釈
@MainActor
final class StickerLibrary {
    static let shared: StickerLibrary = .init()  // OK
}

MainActorデフォルト推論モード

Swift 6.2では、MainActorがデフォルトで推論されるモードが導入されました。手動での注釈は不要です:

// MainActorデフォルト推論が有効な場合:
final class StickerLibrary {
    static let shared: StickerLibrary = .init()  // 暗黙的に@MainActor
}

final class StickerModel {
    let photoProcessor: PhotoProcessor
    var selection: [PhotosPickerItem]  // 暗黙的に@MainActor
}

@MainActor extension StickerModel: Exportable {  // 暗黙的に@MainActor準拠
    func export() {
        photoProcessor.exportAsPNG()
    }
}

このモードはオプトイン形式であり、アプリ、スクリプト、その他の実行可能ターゲットに推奨されます。

核となるパターン — バックグラウンド処理のための@concurrent

実際の並列処理が必要な場合は、@concurrentを使用して明示的にオフロードします:

重要: この例では「親しみやすい並行性」ビルド設定(SE-0466 MainActorデフォルト隔離、SE-0461 非隔離非送信デフォルト)が必要です。これらが有効な場合、extractStickerは呼び出し元のアクターに留まり、可変状態へのアクセスが安全になります。これらの設定がない場合、このコードにはデータ競合が存在します — コンパイラがそれをフラグします。

nonisolated final class PhotoProcessor {
    private var cachedStickers: [String: Sticker] = [:]

    func extractSticker(data: Data, with id: String) async -> Sticker {
        if let sticker = cachedStickers[id] {
            return sticker
        }

        let sticker = await Self.extractSubject(from: data)
        cachedStickers[id] = sticker
        return sticker
    }

    // 負荷の高い処理を並行スレッドプールにオフロード
    @concurrent
    static func extractSubject(from data: Data) async -> Sticker { /* ... */ }
}

// 呼び出し側はawaitする必要があります
let processor = PhotoProcessor()
processedPhotos[item.id] = await processor.extractSticker(data: data, with: item.id)

@concurrentを使用するには:

  1. 包含する型をnonisolatedとしてマーク
  2. 関数に@concurrentを追加
  3. 非同期でない場合はasyncを追加
  4. 呼び出し箇所にawaitを追加

主要な設計上の決定

決定根拠
デフォルトでシングルスレッド最も自然なコードはデータ競合フリー。並行性はオプトイン
asyncは呼び出し元のアクターに留まるデータ競合エラーの原因となった暗黙的オフロードを排除
隔離準拠MainActor型が安全でない回避策なしでプロトコルに準拠可能
@concurrentによる明示的なオプトインバックグラウンド実行は意図的なパフォーマンス選択であり、偶発的なものではない
MainActorデフォルト推論アプリターゲットの@MainActor注釈のボイラープレートを削減
オプトインによる採用非破壊的な移行パス — 機能を段階的に有効化

移行手順

  1. Xcodeで有効化: ビルド設定の「Swift Compiler > Concurrency」セクション
  2. SPMで有効化: パッケージマニフェストでSwiftSettings APIを使用
  3. 移行ツールの使用: swift.org/migration で自動コード変更
  4. MainActorデフォルトから開始: アプリターゲットで推論モードを有効化
  5. 必要な箇所に@concurrentを追加: 最初にプロファイリングし、その後ホットパスをオフロード
  6. 徹底的にテスト: データ競合の問題がコンパイル時エラーになる

ベストプラクティス

  • MainActorから開始 — まずシングルスレッドコードを書き、後で最適化する
  • CPU負荷の高い処理にのみ@concurrentを使用 — 画像処理、圧縮、複雑な計算
  • アプリターゲットでMainActor推論モードを有効化 — ほとんどがシングルスレッドの場合
  • オフロード前にプロファイリング — Instrumentsを使用して実際のボトルネックを見つける
  • グローバルをMainActorで保護 — グローバル/静的可変状態にはアクター隔離が必要
  • nonisolatedの回避策や@Sendableラッパーの代わりに隔離準拠を使用
  • 段階的に移行 — ビルド設定で機能を一度に一つずつ有効化

避けるべきアンチパターン

  • すべてのasync関数に@concurrentを適用する(ほとんどの関数はバックグラウンド実行を必要としない)
  • 隔離を理解せずにnonisolatedを使用してコンパイラエラーを抑制する
  • アクターが同じ安全性を提供するのに、従来のDispatchQueueパターンを維持する
  • 並行性関連のFoundation Modelsコードでmodel.availabilityチェックをスキップする
  • コンパイラと戦う — データ競合が報告された場合、コードには実際の並行性問題が存在する
  • すべてのasyncコードがバックグラウンドで実行されると仮定する(Swift 6.2のデフォルト: 呼び出し元のアクターに留まる)

使用すべき場面

  • すべての新しいSwift 6.2+プロジェクト(親しみやすい並行性が推奨デフォルト)
  • 既存のアプリをSwift 5.xまたは6.0/6.1の並行性から移行する場合
  • Xcode 26採用中にデータ競合安全に関するコンパイラエラーを解決する場合
  • MainActor中心のアプリアーキテクチャを構築する場合(ほとんどのUIアプリ)
  • パフォーマンス最適化 — 特定の負荷の高い計算をバックグラウンドにオフロードする場合

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル