swift-concurrency-expert
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSwift Concurrency Expert
Swift Concurrency 专家
Overview
概述
Review and fix Swift Concurrency issues in Swift 6.2+ codebases by applying actor isolation, Sendable safety, and modern concurrency patterns with minimal behavior changes.
通过应用actor隔离、Sendable安全性和现代并发模式,在最小化行为变更的前提下,审查并修复Swift 6.2+代码库中的Swift并发问题。
Workflow
工作流程
1. Triage the issue
1. 问题分类
- Capture the exact compiler diagnostics and the offending symbol(s).
- Check project concurrency settings: Swift language version (6.2+), strict concurrency level, and whether approachable concurrency (default actor isolation / main-actor-by-default) is enabled.
- Identify the current actor context (,
@MainActor,actor) and whether a default actor isolation mode is enabled.nonisolated - Confirm whether the code is UI-bound or intended to run off the main actor.
- 记录确切的编译器诊断信息和有问题的符号。
- 检查项目并发设置:Swift语言版本(6.2+)、严格并发级别,以及是否启用了易用并发模式(默认actor隔离/默认主线程actor)。
- 识别当前的actor上下文(、
@MainActor、actor),以及是否启用了默认actor隔离模式。nonisolated - 确认代码是否与UI绑定,或是打算在主线程actor之外运行。
2. Apply the smallest safe fix
2. 应用最小化的安全修复
Prefer edits that preserve existing behavior while satisfying data-race safety.
Common fixes:
- UI-bound types: annotate the type or relevant members with .
@MainActor - Protocol conformance on main actor types: make the conformance isolated (e.g., ).
extension Foo: @MainActor SomeProtocol - Global/static state: protect with or move into an actor.
@MainActor - Background work: move expensive work into a async function on a
@concurrenttype or use annonisolatedto guard mutable state.actor - Sendable errors: prefer immutable/value types; add conformance only when correct; avoid
Sendableunless you can prove thread safety.@unchecked Sendable
优先选择在保留现有行为的同时满足数据竞争安全性的修改。
常见修复方案:
- UI绑定类型:为类型或相关成员添加注解。
@MainActor - 主线程actor类型的协议一致性:使一致性变为隔离的(例如:)。
extension Foo: @MainActor SomeProtocol - 全局/静态状态:使用保护,或移入actor中。
@MainActor - 后台任务:将耗时任务移至类型的
nonisolated异步函数中,或使用@concurrent来保护可变状态。actor - Sendable错误:优先使用不可变/值类型;仅在正确的情况下添加一致性;除非能证明线程安全,否则避免使用
Sendable。@unchecked Sendable
Reference material
参考资料
- See for Swift 6.2 changes, patterns, and examples.
references/swift-6-2-concurrency.md - See when the project is opted into approachable concurrency mode.
references/approachable-concurrency.md - See for SwiftUI-specific concurrency guidance.
references/swiftui-concurrency-tour-wwdc.md
- 有关Swift 6.2的变更、模式和示例,请参阅。
references/swift-6-2-concurrency.md - 当项目启用易用并发模式时,请参阅。
references/approachable-concurrency.md - 有关SwiftUI特定的并发指南,请参阅。
references/swiftui-concurrency-tour-wwdc.md