swift-concurrency-6-2 by affaan-m/everything-claude-code
npx skills add https://github.com/affaan-m/everything-claude-code --skill swift-concurrency-6-2采用 Swift 6.2 并发模型的模式,其中代码默认在单线程中运行,并发是显式引入的。在无需牺牲性能的前提下消除常见的数据竞争错误。
在 Swift 6.1 及更早版本中,异步函数可能被隐式卸载到后台线程,导致即使在看似安全的代码中也会出现数据竞争错误:
// Swift 6.1: ERROR
@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 }
// Error: Sending 'self.photoProcessor' risks causing data races
return await photoProcessor.extractSticker(data: data, with: item.itemIdentifier)
}
}
Swift 6.2 修复了此问题:异步函数默认保持在调用方所在的 actor 上。
// Swift 6.2: OK — async stays on MainActor, no data race
@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)
}
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
MainActor 类型现在可以安全地遵循非隔离协议:
protocol Exportable {
func export()
}
// Swift 6.1: ERROR — crosses into main actor-isolated code
// Swift 6.2: OK with isolated conformance
extension StickerModel: @MainActor Exportable {
func export() {
photoProcessor.exportAsPNG()
}
}
编译器确保一致性仅在主 actor 上使用:
// OK — ImageExporter is also @MainActor
@MainActor
struct ImageExporter {
var items: [any Exportable]
mutating func add(_ item: StickerModel) {
items.append(item) // Safe: same actor isolation
}
}
// ERROR — nonisolated context can't use MainActor conformance
nonisolated struct ImageExporter {
var items: [any Exportable]
mutating func add(_ item: StickerModel) {
items.append(item) // Error: Main actor-isolated conformance cannot be used here
}
}
使用 MainActor 保护全局/静态状态:
// Swift 6.1: ERROR — non-Sendable type may have shared mutable state
final class StickerLibrary {
static let shared: StickerLibrary = .init() // Error
}
// Fix: Annotate with @MainActor
@MainActor
final class StickerLibrary {
static let shared: StickerLibrary = .init() // OK
}
Swift 6.2 引入了一种模式,默认推断 MainActor — 无需手动注解:
// With MainActor default inference enabled:
final class StickerLibrary {
static let shared: StickerLibrary = .init() // Implicitly @MainActor
}
final class StickerModel {
let photoProcessor: PhotoProcessor
var selection: [PhotosPickerItem] // Implicitly @MainActor
}
extension StickerModel: Exportable { // Implicitly @MainActor conformance
func export() {
photoProcessor.exportAsPNG()
}
}
此模式是可选的,推荐用于应用、脚本和其他可执行目标。
当需要真正的并行性时,使用 @concurrent 显式卸载:
重要提示: 此示例需要易用并发构建设置 — SE-0466(MainActor 默认隔离)和 SE-0461(默认非隔离非发送)。启用这些设置后,
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
}
// Offload expensive work to concurrent thread pool
@concurrent
static func extractSubject(from data: Data) async -> Sticker { /* ... */ }
}
// Callers must await
let processor = PhotoProcessor()
processedPhotos[item.id] = await processor.extractSticker(data: data, with: item.id)
要使用 @concurrent:
nonisolated@concurrentasyncawait| 决策 | 理由 |
|---|---|
| 默认单线程 | 大多数自然代码没有数据竞争;并发是可选的 |
| 异步保持在调用方 actor | 消除了导致数据竞争错误的隐式卸载 |
| 隔离一致性 | MainActor 类型可以遵循协议,无需不安全的变通方法 |
@concurrent 显式选择加入 | 后台执行是深思熟虑的性能选择,而非偶然 |
| MainActor 默认推断 | 减少应用目标的样板 @MainActor 注解 |
| 选择性采用 | 非破坏性迁移路径 — 逐步启用功能 |
SwiftSettings API@concurrent:先进行性能分析,然后卸载热点路径@concurrent — 图像处理、压缩、复杂计算nonisolated 变通方法或 @Sendable 包装器@concurrent(大多数不需要后台执行)nonisolated 来抑制编译器错误DispatchQueue 模式model.availability 检查每周安装量
824
仓库
GitHub 星标
102.1K
首次出现
2026年2月24日
安全审计
已安装于
codex783
cursor691
gemini-cli689
github-copilot687
amp687
opencode687
Patterns for adopting Swift 6.2's concurrency model where code runs single-threaded by default and concurrency is introduced explicitly. Eliminates common data-race errors without sacrificing performance.
In Swift 6.1 and earlier, async functions could be implicitly offloaded to background threads, causing data-race errors even in seemingly safe code:
// Swift 6.1: ERROR
@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 }
// Error: Sending 'self.photoProcessor' risks causing data races
return await photoProcessor.extractSticker(data: data, with: item.itemIdentifier)
}
}
Swift 6.2 fixes this: async functions stay on the calling actor by default.
// Swift 6.2: OK — async stays on MainActor, no data race
@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 types can now conform to non-isolated protocols safely:
protocol Exportable {
func export()
}
// Swift 6.1: ERROR — crosses into main actor-isolated code
// Swift 6.2: OK with isolated conformance
extension StickerModel: @MainActor Exportable {
func export() {
photoProcessor.exportAsPNG()
}
}
The compiler ensures the conformance is only used on the main actor:
// OK — ImageExporter is also @MainActor
@MainActor
struct ImageExporter {
var items: [any Exportable]
mutating func add(_ item: StickerModel) {
items.append(item) // Safe: same actor isolation
}
}
// ERROR — nonisolated context can't use MainActor conformance
nonisolated struct ImageExporter {
var items: [any Exportable]
mutating func add(_ item: StickerModel) {
items.append(item) // Error: Main actor-isolated conformance cannot be used here
}
}
Protect global/static state with MainActor:
// Swift 6.1: ERROR — non-Sendable type may have shared mutable state
final class StickerLibrary {
static let shared: StickerLibrary = .init() // Error
}
// Fix: Annotate with @MainActor
@MainActor
final class StickerLibrary {
static let shared: StickerLibrary = .init() // OK
}
Swift 6.2 introduces a mode where MainActor is inferred by default — no manual annotations needed:
// With MainActor default inference enabled:
final class StickerLibrary {
static let shared: StickerLibrary = .init() // Implicitly @MainActor
}
final class StickerModel {
let photoProcessor: PhotoProcessor
var selection: [PhotosPickerItem] // Implicitly @MainActor
}
extension StickerModel: Exportable { // Implicitly @MainActor conformance
func export() {
photoProcessor.exportAsPNG()
}
}
This mode is opt-in and recommended for apps, scripts, and other executable targets.
When you need actual parallelism, explicitly offload with @concurrent:
Important: This example requires Approachable Concurrency build settings — SE-0466 (MainActor default isolation) and SE-0461 (NonisolatedNonsendingByDefault). With these enabled,
extractStickerstays on the caller's actor, making mutable state access safe. Without these settings, this code has a data race — the compiler will flag it.
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
}
// Offload expensive work to concurrent thread pool
@concurrent
static func extractSubject(from data: Data) async -> Sticker { /* ... */ }
}
// Callers must await
let processor = PhotoProcessor()
processedPhotos[item.id] = await processor.extractSticker(data: data, with: item.id)
To use @concurrent:
nonisolated@concurrent to the functionasync if not already asynchronousawait at call sites| Decision | Rationale |
|---|---|
| Single-threaded by default | Most natural code is data-race free; concurrency is opt-in |
| Async stays on calling actor | Eliminates implicit offloading that caused data-race errors |
| Isolated conformances | MainActor types can conform to protocols without unsafe workarounds |
@concurrent explicit opt-in | Background execution is a deliberate performance choice, not accidental |
| MainActor default inference | Reduces boilerplate @MainActor annotations for app targets |
| Opt-in adoption | Non-breaking migration path — enable features incrementally |
SwiftSettings API in package manifest@concurrent where needed: Profile first, then offload hot paths@concurrent only for CPU-intensive work — image processing, compression, complex computationnonisolated workarounds or @Sendable wrappers@concurrent to every async function (most don't need background execution)nonisolated to suppress compiler errors without understanding isolationDispatchQueue patterns when actors provide the same safetymodel.availability checks in concurrency-related Foundation Models codeWeekly Installs
824
Repository
GitHub Stars
102.1K
First Seen
Feb 24, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex783
cursor691
gemini-cli689
github-copilot687
amp687
opencode687
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
百度AI搜索技能:集成百度千帆平台,支持网页/百科/AI智能搜索,提升开发效率
775 周安装
Playwright 交互式测试技能:持久会话调试本地Web/Electron应用,无需重启工具链
775 周安装
HumanizerAI 人性化工具:一键将 AI 文本转化为自然人类写作,绕过 AI 检测
776 周安装
iOS调试器代理 - 自动化Xcode模拟器构建、UI交互与日志捕获工具
777 周安装
App Store优化 (ASO) 技能 - 移动应用商店关键词研究、元数据优化与转化率提升
778 周安装
安全最佳实践指南:识别语言框架漏洞,编写安全代码与生成修复报告
779 周安装