swift-concurrency-expert

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Swift 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
    ,
    nonisolated
    ) and whether a default actor isolation mode is enabled.
  • Confirm whether the code is UI-bound or intended to run off the main actor.
  • 记录确切的编译器诊断信息和有问题的符号。
  • 检查项目并发设置:Swift语言版本(6.2+)、严格并发级别,以及是否启用了易用并发模式(默认actor隔离/默认主线程actor)。
  • 识别当前的actor上下文(
    @MainActor
    actor
    nonisolated
    ),以及是否启用了默认actor隔离模式。
  • 确认代码是否与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
    @MainActor
    or move into an actor.
  • Background work: move expensive work into a
    @concurrent
    async function on a
    nonisolated
    type or use an
    actor
    to guard mutable state.
  • Sendable errors: prefer immutable/value types; add
    Sendable
    conformance only when correct; avoid
    @unchecked Sendable
    unless you can prove thread safety.
优先选择在保留现有行为的同时满足数据竞争安全性的修改。
常见修复方案:
  • UI绑定类型:为类型或相关成员添加
    @MainActor
    注解。
  • 主线程actor类型的协议一致性:使一致性变为隔离的(例如:
    extension Foo: @MainActor SomeProtocol
    )。
  • 全局/静态状态:使用
    @MainActor
    保护,或移入actor中。
  • 后台任务:将耗时任务移至
    nonisolated
    类型的
    @concurrent
    异步函数中,或使用
    actor
    来保护可变状态。
  • Sendable错误:优先使用不可变/值类型;仅在正确的情况下添加
    Sendable
    一致性;除非能证明线程安全,否则避免使用
    @unchecked Sendable

Reference material

参考资料

  • See
    references/swift-6-2-concurrency.md
    for Swift 6.2 changes, patterns, and examples.
  • See
    references/approachable-concurrency.md
    when the project is opted into approachable concurrency mode.
  • See
    references/swiftui-concurrency-tour-wwdc.md
    for SwiftUI-specific concurrency guidance.
  • 有关Swift 6.2的变更、模式和示例,请参阅
    references/swift-6-2-concurrency.md
  • 当项目启用易用并发模式时,请参阅
    references/approachable-concurrency.md
  • 有关SwiftUI特定的并发指南,请参阅
    references/swiftui-concurrency-tour-wwdc.md