modern-swift
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseModern Swift (6.2+)
现代Swift(6.2+)
Swift 6.2 introduces strict compile-time concurrency checking with async/await, actors, and Sendable constraints that prevent data races at compile time instead of runtime. This is the foundation of safe concurrent Swift.
Swift 6.2引入了基于async/await、actors和Sendable约束的严格编译期并发检查,可在编译阶段而非运行时防止数据竞争。这是Swift安全并发的基础。
Overview
概述
Modern Swift replaces older concurrency patterns (completion handlers, DispatchQueue, locks) with compiler-enforced safety. The core principle: if it compiles with strict concurrency enabled, it cannot have data races.
现代Swift用编译器强制的安全机制取代了旧的并发模式(完成处理程序、DispatchQueue、锁)。核心原则:在启用严格并发检查的情况下能编译通过的代码,不会存在数据竞争。
Quick Reference
快速参考
| Need | Use | NOT |
|---|---|---|
| Async operation | | Completion handlers |
| Main thread work | | |
| Shared mutable state | | Locks, serial queues |
| Parallel tasks | | |
| Thread safety | | |
| 需求 | 推荐用法 | 不推荐用法 |
|---|---|---|
| 异步操作 | | 完成处理程序 |
| 主线程任务 | | |
| 可变共享状态 | | 锁、串行队列 |
| 并行任务 | | |
| 线程安全 | | 到处使用 |
Core Workflow
核心工作流程
When writing async Swift code:
- Mark async functions with , call with
asyncawait - Apply to view models and UI-updating code
@MainActor - Use instead of locks for shared mutable state
actor - Check or call
Task.isCancelledin loopsTask.checkCancellation() - Enable strict concurrency in Package.swift for compile-time safety
编写异步Swift代码时:
- 用标记异步函数,调用时使用
asyncawait - 为视图模型和UI更新代码添加
@MainActor - 使用而非锁来管理可变共享状态
actor - 在循环中检查或调用
Task.isCancelledTask.checkCancellation() - 在Package.swift中启用严格并发检查以获得编译期安全保障
Reference Loading Guide
参考资料加载指南
ALWAYS load reference files if there is even a small chance the content may be required. It's better to have the context than to miss a pattern or make a mistake.
| Reference | Load When |
|---|---|
| Concurrency Essentials | Writing async code, converting completion handlers, using |
| Swift 6 Concurrency | Using |
| Task Groups | Running multiple async operations in parallel |
| Task Cancellation | Implementing long-running or cancellable operations |
| Strict Concurrency | Enabling Swift 6 strict mode or fixing Sendable errors |
| Macros | Using or understanding Swift macros like |
| Modern Attributes | Migrating legacy code or using |
| Migration Patterns | Modernizing delegate patterns or UIKit views |
只要有哪怕一丝可能需要用到相关内容,就一定要加载参考文件。 拥有上下文总比遗漏模式或犯错要好。
| 参考资料 | 加载场景 |
|---|---|
| 并发基础 | 编写异步代码、转换完成处理程序、使用 |
| Swift 6并发 | 使用 |
| 任务组 | 并行运行多个异步操作时 |
| 任务取消 | 实现长时间运行或可取消的操作时 |
| 严格并发 | 启用Swift 6严格模式或修复Sendable错误时 |
| 宏 | 使用或理解Swift宏(如 |
| 现代属性 | 迁移遗留代码或使用 |
| 迁移模式 | 现代化委托模式或UIKit视图时 |
Common Mistakes
常见错误
-
as a quick fix — Using
@unchecked Sendableto silence compiler errors means you've opted out of safety. If the error persists after@unchecked Sendable, your code has a potential data race. Fix the underlying issue instead.@unchecked -
Missingat call sites — Forgetting
awaitwhen calling async functions is a compiler error, but checkingawaitin a loop without callingTask.isCancelledsilently ignores cancellation.Task.checkCancellation() -
Capturingin async blocks without
self— Holding a strong reference toweakin a long-running async task prevents deinit. Always useselfin closures or use[weak self]which auto-manages the lifecycle..task -
Not checking task cancellation — Long-running operations should regularly checkor call
Task.isCancelled, otherwise cancellation signals are ignored.Task.checkCancellation() -
Forgettingon UI code and test suites — Main test struct and view models that update
@MainActorproperties need@Published. Forgetting it silently allows cross-thread mutations. Apply@MainActorto: view models, view structs, main test structs, and any type that touches UI.@MainActor -
Actor re-entrancy surprises —inside an actor method can release the lock temporarily. Another task may modify actor state. Design actor methods assuming state can change between
awaitpoints.await
-
用快速解决问题 —— 使用
@unchecked Sendable来掩盖编译器错误意味着你主动放弃了安全保障。如果添加@unchecked Sendable后错误仍然存在,说明你的代码存在潜在的数据竞争。应修复根本问题而非掩盖错误。@unchecked -
调用异步函数时遗漏—— 调用异步函数时忘记写
await会触发编译器错误,但在循环中仅检查await却不调用Task.isCancelled会悄悄忽略取消信号。Task.checkCancellation() -
在异步块中捕获时未使用
self—— 在长时间运行的异步任务中强引用weak会阻止对象被销毁。在闭包中务必使用self,或使用[weak self]来自动管理生命周期。.task -
未检查任务取消状态 —— 长时间运行的操作应定期检查或调用
Task.isCancelled,否则取消信号会被忽略。Task.checkCancellation() -
UI代码和测试套件遗漏—— 更新
@MainActor属性的主测试结构体和视图模型需要添加@Published。遗漏该属性会悄悄允许跨线程修改。请为以下类型添加@MainActor:视图模型、视图结构体、主测试结构体以及任何涉及UI的类型。@MainActor -
Actor重入意外 —— Actor方法内部的会临时释放锁。其他任务可能会修改Actor的状态。设计Actor方法时,要假设
await点之间的状态可能发生变化。await