Communitygithub.com

Swift 6.2 可近式並行處理

Swift 6.2 預設單執行緒,使用 @concurrent 明確卸載背景任務,並為主執行緒型別提供隔離符合。適用於採用 Swift 6.2 並行模型,透過 @concurrent 卸載或解決主執行緒隔離問題。

Swift 6.2 可近式並行處理 是什麼?

Swift 6.2 可近式並行處理技能,旨在協助開發者無縫遷移至 Swift 6.2 的並行模型,該模型預設為單執行緒執行,並在必要時明確引入並行性。此模型透過消除隱含的背景卸載,大幅減少資料競爭錯誤,同時不犧牲效能。技能詳細說明如何使用 @concurrent 屬性將 CPU 密集型工作卸載到背景執行緒,並介紹隔離符合(isolated conformance)功能,讓 MainActor 型別能安全地符合非隔離協定。此外,也涵蓋 MainActor 預設推斷模式,可減少手動註解,並提供全域與靜態變數的保護模式。適用於 Xcode 26 及 Swift 6.2 專案,支援逐步遷移,並提供詳細的遷移步驟、最佳實踐與應避免的反模式。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

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 函式預設停留在呼叫方的 actor 上。

// Swift 6.2:正確 — 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:錯誤 — 跨越到 main actor 隔離的程式碼
// Swift 6.2:正確,使用隔離符合
extension StickerModel: @MainActor Exportable {
    func export() {
        photoProcessor.exportAsPNG()
    }
}

編譯器確保此符合僅在 main actor 上使用:

// 正確 — ImageExporter 也是 @MainActor
@MainActor
struct ImageExporter {
    var items: [any Exportable]

    mutating func add(_ item: StickerModel) {
        items.append(item)  // 安全:相同的 actor 隔離
    }
}

// 錯誤 — 非隔離上下文不能使用 MainActor 符合
nonisolated struct ImageExporter {
    var items: [any Exportable]

    mutating func add(_ item: StickerModel) {
        items.append(item)  // 錯誤:此處不能使用 MainActor 隔離的符合
    }
}

核心模式 — 全域與靜態變數

使用 MainActor 保護全域/靜態狀態:

// Swift 6.1:錯誤 — 非 Sendable 型別可能具有共享的可變狀態
final class StickerLibrary {
    static let shared: StickerLibrary = .init()  // 錯誤
}

// 修正:使用 @MainActor 註解
@MainActor
final class StickerLibrary {
    static let shared: StickerLibrary = .init()  // 正確
}

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 會保留在呼叫方的 actor 上,使可變狀態存取變得安全。若未啟用這些設定,此程式碼會存在資料競爭 — 編譯器會標記它。

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 保留在呼叫方的 actor 上消除導致資料競爭錯誤的隱含卸載
隔離符合MainActor 型別可以符合協定,而無需不安全的解決方法
@concurrent 明確選擇加入背景執行是審慎的效能選擇,而非偶然
MainActor 預設推斷減少應用程式目標的樣板 @MainActor 註解
選擇性加入採用非破壞性的遷移路徑 — 逐步啟用功能

遷移步驟

  1. 在 Xcode 中啟用:Swift 編譯器 > 建置設定中的 Concurrency 區段
  2. 在 SPM 中啟用:在套件清單中使用 SwiftSettings API
  3. 使用遷移工具:透過 swift.org/migration 進行自動程式碼變更
  4. 從 MainActor 預設值開始:為應用程式目標啟用推斷模式
  5. 在需要的地方新增 @concurrent:先進行效能分析,然後卸載熱門路徑
  6. 徹底測試:資料競爭問題會變成編譯時期錯誤

最佳實踐

  • 從 MainActor 開始 — 先編寫單執行緒程式碼,之後再最佳化
  • 僅對 CPU 密集型工作使用 @concurrent — 影像處理、壓縮、複雜計算
  • 為主要單執行緒的應用程式目標啟用 MainActor 推斷模式
  • 在卸載前進行效能分析 — 使用 Instruments 找出實際瓶頸
  • 使用 MainActor 保護全域變數 — 全域/靜態可變狀態需要 actor 隔離
  • 使用隔離符合,而不是 nonisolated 解決方法或 @Sendable 包裝器
  • 逐步遷移 — 在建置設定中一次啟用一個功能

應避免的反模式

  • 對每個 async 函式套用 @concurrent(大多數不需要背景執行)
  • 使用 nonisolated 來壓制編譯器錯誤,而不了解隔離
  • 當 actor 提供相同安全性時,仍保留舊的 DispatchQueue 模式
  • 跳過並行相關 Foundation 模型程式碼中的 model.availability 檢查
  • 與編譯器對抗 — 如果它報告資料競爭,表示程式碼確實存在並行問題
  • 假設所有 async 程式碼都在背景執行(Swift 6.2 預設:保留在呼叫方的 actor 上)

何時使用

  • 所有新的 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.

相關技能