Communitygithub.com

swift-concurrency-6-2

Swift 6.2 可親近的並行處理 — 預設單執行緒,以 @concurrent 明確卸載背景工作,為主執行緒類型提供隔離一致性。適用於採用 Swift 6.2 並行處理時,以 @concurrent 卸載或解決主執行緒隔離問題。

swift-concurrency-6-2 是什麼?

這個技能專注於 Swift 6.2 的「可親近的並行處理」(Approachable Concurrency)模型。其主要目標是讓程式碼預設為單執行緒執行,並要求開發者以 `@concurrent` 關鍵字明確地將工作卸載到背景,從而從根本上消除資料競爭錯誤。此模型解決了 Swift 6.1 及更早版本中非同步函數可能被隱含地卸載到背景執行緒所導致的難以追蹤的資料競爭問題。對於需要遷移到 Swift 6.2 的專案、遇到資料競爭安全編譯錯誤的開發者,以及建構以 MainActor 為中心的應用程式架構的開發者而言,這項技能至關重要。它支援 Xcode 26 等 IDE,並透過 `SwiftSettings` API 支援 Swift Package Manager。其核心模式包括:為 MainActor 類型提供隔離一致性(isolated conformances)、以 `@MainActor` 保護全域/靜態變數、引入 MainActor 預設推斷模式以減少 `@MainActor` 標註樣板程式碼,以及使用 `@concurrent` 關鍵字進行明確的背景工作卸載。此技能提供了詳細的遷移步驟、最佳實踐(例如先撰寫單執行緒程式碼再優化)以及應避免的反模式(例如對每個非同步函數都使用 `@concurrent`)。它代表了在 Swift 中處理並行處理的推薦預設方式,從而在不犧牲效能的前提下,將大多數資料競爭錯誤變為編譯時期錯誤。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/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 及更早版本中,非同步函數可能被隱含地卸載到背景執行緒,即使在看似安全的程式碼中也可能導致資料競爭錯誤:

// 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 修正了此問題:非同步函數預設會停留在呼叫的參與者(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()
    }
}

編譯器確保此一致性僅在主執行緒上使用:

// 正常 — 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:錯誤 — 非 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 會停留在呼叫端的參與者上,從而確保可變狀態存取安全。若未啟用這些設定,此程式碼存在資料競爭 — 編譯器將會標記它。

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 編譯器 > 並行處理章節
  2. 在 SPM 中啟用:在套件清單中使用 SwiftSettings API
  3. 使用遷移工具:透過 swift.org/migration 進行自動程式碼變更
  4. 從 MainActor 預設值開始:為應用程式目標啟用推斷模式
  5. 在需要的地方新增 @concurrent:先進行效能分析,再卸載熱點路徑
  6. 徹底測試:資料競爭問題將變為編譯時期錯誤

最佳實踐

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

應避免的反模式

  • 對每個非同步函數都使用 @concurrent(大多數不需要背景執行)
  • 在不了解隔離的情況下使用 nonisolated 抑制編譯器錯誤
  • 當參與者能提供相同安全性時,仍保留舊的 DispatchQueue 模式
  • 在與並行相關的 Foundation Models 程式碼中跳過 model.availability 檢查
  • 與編譯器對抗 — 如果它報告資料競爭,則程式碼確實存在並行問題
  • 假設所有非同步程式碼都在背景執行(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.

相關技能