Communitygithub.com

swift-concurrency-6-2

Swift 6.2 アプローチ可能な並行処理 — デフォルトでシングルスレッド、@concurrent で明示的なバックグラウンドオフロード、メインアクター型のための分離準拠。Swift 6.2 の並行処理を採用する際に使用します — @concurrent によるオフロードやメインアクター分離の解決。

swift-concurrency-6-2 とは?

このスキルは、Swift 6.2 の「アプローチ可能な並行処理(Approachable Concurrency)」モデルを採用するためのパターンを提供します。このモデルでは、コードはデフォルトでシングルスレッドで実行され、並行処理は明示的に導入されます。これにより、一般的なデータ競合エラーを排除しつつ、パフォーマンスを犠牲にしません。主に、Swift 5.x や 6.0/6.1 からのプロジェクト移行時、データ競合安全性に関するコンパイラエラーの解決、MainActor ベースのアプリケーションアーキテクチャの設計、CPU 負荷の高い処理のバックグラウンドスレッドへのオフロード、MainActor 分離型でのプロトコル準拠の実装、Xcode 26 でのアプローチ可能な並行処理ビルド設定の有効化といった場面で使用します。 このスキルは、Swift 6.2 の主要なパターン(デフォルトでシングルスレッド、async は呼び出し元のアクターに留まる、分離準拠、@concurrent による明示的なバックグラウンド実行、MainActor のデフォルト推論)を解説し、移行手順、ベストプラクティス、避けるべきアンチパターンを提供します。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/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
extension StickerModel: @MainActor 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 で保護:

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

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

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

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

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

重要: この例にはアプローチ可能な並行処理のビルド設定が必要です — SE-0466 (MainActor デフォルト分離) と SE-0461 (NonisolatedNonsendingByDefault)。これらを有効にすると、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 から開始 — まずシングルスレッドコードを書き、後で最適化
  • @concurrent は CPU 負荷の高い処理にのみ使用 — 画像処理、圧縮、複雑な計算
  • アプリターゲットでは 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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

関連スキル