swift_concurrency
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSwift Concurrency
Swift并发编程
This skill covers Swift's modern concurrency features from Swift 5.5 through Swift 6, including async/await, structured concurrency, actors, and Swift 6's strict data-race safety.
本技能涵盖了Swift 5.5到Swift 6的现代并发特性,包括async/await、结构化并发、Actor以及Swift 6的严格数据竞争安全机制。
Overview
概述
Swift's modern concurrency model provides a safer, more intuitive way to write asynchronous code. Swift 6 takes this further with compile-time data-race safety, turning potential concurrency bugs into compiler errors.
Swift的现代并发模型提供了一种更安全、更直观的异步代码编写方式。Swift 6更进一步,引入了编译期数据竞争安全机制,将潜在的并发bug转化为编译错误。
Available References
可用参考资料
Swift 6 & Strict Concurrency
Swift 6 & 严格并发
- Swift 6 Strict Mode - Complete concurrency checking, data race prevention
- Sendable Protocol - Sendable conformance, @Sendable closures, thread safety
- Isolation & Actors - @MainActor, global actors, region-based isolation
- Swift 6严格模式 - 完整并发检查、数据竞争预防
- Sendable协议 - Sendable合规性、@Sendable闭包、线程安全
- 隔离机制与Actor - @MainActor、全局Actor、基于区域的隔离
Core Concurrency
核心并发特性
- Async/Await - Asynchronous functions, Task, TaskGroup, Actor basics
- Async/Await - 异步函数、Task、TaskGroup、Actor基础
Swift 6 Highlights
Swift 6核心亮点
Strict Concurrency by Default
默认启用严格并发
Swift 6 enforces data-race safety at compile time:
swift
// ❌ Compile-time error in Swift 6
var globalCounter = 0
func increment() {
globalCounter += 1 // Error: concurrent access
}
// ✅ Safe with actor isolation
actor Counter {
private var value = 0
func increment() { value += 1 }
}Swift 6在编译期强制实施数据竞争安全:
swift
// ❌ Swift 6中会触发编译错误
var globalCounter = 0
func increment() {
globalCounter += 1 // 错误:并发访问
}
// ✅ 用Actor隔离实现安全访问
actor Counter {
private var value = 0
func increment() { value += 1 }
}Sendable Protocol
Sendable协议
Mark types safe to share across concurrency boundaries:
swift
struct User: Sendable {
let id: Int
let name: String
}
@Sendable func process() async {
// Captures must be Sendable
}标记可在并发边界安全共享的类型:
swift
struct User: Sendable {
let id: Int
let name: String
}
@Sendable func process() async {
// 捕获的变量必须符合Sendable
}MainActor & Global Actors
MainActor与全局Actor
swift
@MainActor
class ViewModel: ObservableObject {
@Published var items = [Item]()
}
@globalActor
actor DatabaseActor {
static let shared = DatabaseActor()
private init() {}
}swift
@MainActor
class ViewModel: ObservableObject {
@Published var items = [Item]()
}
@globalActor
actor DatabaseActor {
static let shared = DatabaseActor()
private init() {}
}Quick Reference
快速参考
Async/Await Basics
Async/Await基础
swift
func fetchData() async throws -> Data {
let (data, _) = try await URLSession.shared.data(from: url)
return data
}swift
func fetchData() async throws -> Data {
let (data, _) = try await URLSession.shared.data(from: url)
return data
}Swift 6 Migration Checklist
Swift 6迁移检查清单
- Enable Swift 6 language mode
- Enable strict concurrency checking
- Wrap global mutable state in actors
- Add Sendable conformance to types
- Fix non-Sendable captures in @Sendable closures
- Isolate UI code with @MainActor
- Audit third-party dependencies
- 启用Swift 6语言模式
- 启用严格并发检查
- 用Actor封装全局可变状态
- 为类型添加Sendable合规性
- 修复@Sendable闭包中的非Sendable捕获问题
- 用@MainActor隔离UI代码
- 审核第三方依赖
Running Async Code
运行异步代码
swift
// Fire-and-forget
Task {
let result = await asyncOperation()
}
// With priority
Task(priority: .background) {
await heavyComputation()
}
// With cancellation
let task = Task {
try await longRunningOperation()
}
task.cancel()swift
// 即发即弃
Task {
let result = await asyncOperation()
}
// 带优先级
Task(priority: .background) {
await heavyComputation()
}
// 支持取消
let task = Task {
try await longRunningOperation()
}
task.cancel()Concurrent Operations
并发操作
swift
// Async let (parallel await)
async let task1 = fetchUser()
async let task2 = fetchSettings()
let (user, settings) = try await (task1, task2)
// TaskGroup
try await withThrowingTaskGroup(of: Item.self) { group in
for id in ids {
group.addTask { try await fetchItem(id: id) }
}
return try await group.reduce(into: []) { $0.append($1) }
}swift
// Async let(并行等待)
async let task1 = fetchUser()
async let task2 = fetchSettings()
let (user, settings) = try await (task1, task2)
// TaskGroup
try await withThrowingTaskGroup(of: Item.self) { group in
for id in ids {
group.addTask { try await fetchItem(id: id) }
}
return try await group.reduce(into: []) { $0.append($1) }
}Actor Thread Safety
Actor线程安全
swift
actor BankAccount {
private var balance: Double = 0
func deposit(_ amount: Double) {
balance += amount
}
func getBalance() -> Double {
return balance
}
}
let account = BankAccount()
await account.deposit(100)swift
actor BankAccount {
private var balance: Double = 0
func deposit(_ amount: Double) {
balance += amount
}
func getBalance() -> Double {
return balance
}
}
let account = BankAccount()
await account.deposit(100)Isolation Boundaries
隔离边界
swift
// Crossing isolation boundaries
@MainActor
func updateUI() async {
// On main thread
let data = await fetchData() // Switch to non-isolated
label.text = data // Back to main thread
}
// Region transfer
func process() async {
let data = Data() // Disconnected
await save(data) // Transfer to actor
// ❌ Can't use data here anymore
}swift
// 跨越隔离边界
@MainActor
func updateUI() async {
// 处于主线程
let data = await fetchData() // 切换到非隔离环境
label.text = data // 回到主线程
}
// 区域转移
func process() async {
let data = Data() // 无关联隔离
await save(data) // 转移到Actor环境
// ❌ 此处无法再使用data
}Swift 6 vs Swift 5.x
Swift 6与Swift 5.x对比
| Feature | Swift 5.x | Swift 6 |
|---|---|---|
| Concurrency checking | Warnings | Errors |
| Data race safety | Runtime | Compile-time |
| Sendable enforcement | Opt-in | Required |
| Global variable safety | Warning | Error |
| Strict mode | Experimental | Default |
| 特性 | Swift 5.x | Swift 6 |
|---|---|---|
| 并发检查 | 警告 | 错误 |
| 数据竞争安全 | 运行时 | 编译期 |
| Sendable强制 | 可选启用 | 必填 |
| 全局变量安全 | 警告 | 错误 |
| 严格模式 | 实验性 | 默认 |
Best Practices
最佳实践
Swift 6 Best Practices
Swift 6最佳实践
- Enable Swift 6 mode early - Start migration now
- Use actors for shared state - Default to actors over locks
- Design Sendable types - Make types Sendable from the start
- Isolate UI with @MainActor - All UI code on main thread
- Respect isolation regions - Don't use values after transfer
- Leverage compile-time safety - Let compiler catch data races
- Create domain actors - Custom global actors for heavy work
- 尽早启用Swift 6模式 - 现在就开始迁移
- 用Actor管理共享状态 - 优先使用Actor而非锁
- 设计Sendable类型 - 从一开始就让类型支持Sendable
- 用@MainActor隔离UI代码 - 所有UI代码在主线程执行
- 遵守隔离区域规则 - 转移后不再使用原数据
- 利用编译期安全 - 让编译器捕获数据竞争问题
- 创建领域Actor - 为繁重工作自定义全局Actor
General Concurrency
通用并发最佳实践
- Prefer async/await - Over completion handlers
- Use structured concurrency - Clear task hierarchies
- Handle cancellation - Check Task.isCancelled
- Use value types - Immutable data is thread-safe
- Avoid shared mutable state - Or protect with actors
- 优先使用async/await - 替代完成处理闭包
- 使用结构化并发 - 清晰的任务层级
- 处理取消操作 - 检查Task.isCancelled
- 使用值类型 - 不可变数据天生线程安全
- 避免共享可变状态 - 或用Actor保护
Migration from Completion Handlers
从完成处理闭包迁移
swift
// Before (Swift 5)
func fetchUser(completion: @escaping (Result<User, Error>) -> Void) {
URLSession.shared.dataTask(with: url) { data, response, error in
// Handle result
completion(result)
}.resume()
}
// After (Swift 6)
func fetchUser() async throws -> User {
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}swift
// 之前(Swift 5)
func fetchUser(completion: @escaping (Result<User, Error>) -> Void) {
URLSession.shared.dataTask(with: url) { data, response, error in
// 处理结果
completion(result)
}.resume()
}
// 之后(Swift 6)
func fetchUser() async throws -> User {
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}Common Swift 6 Errors
Swift 6常见错误
| Error | Quick Fix |
|---|---|
| Concurrent access to global | Wrap in actor |
| Non-Sendable in @Sendable | Make type Sendable |
| Actor isolation violation | Add await or change isolation |
| Use after transfer | Use before transfer or copy value |
| Main actor isolation | Add @MainActor annotation |
| 错误 | 快速修复方案 |
|---|---|
| 全局变量并发访问 | 用Actor封装 |
| @Sendable中存在非Sendable类型 | 让类型支持Sendable |
| 违反Actor隔离规则 | 添加await或修改隔离设置 |
| 转移后使用数据 | 在转移前使用或复制数据 |
| 主线程Actor隔离问题 | 添加@MainActor注解 |
Resources
资源链接
- Swift Evolution: https://github.com/apple/swift-evolution
- SE-0412: Strict concurrency for global variables
- SE-0471: SerialExecutor isolation checking
- SE-0430: Sending parameters
- SE-0414: Region-based isolation
- Apple Docs: https://developer.apple.com/documentation/swift/concurrency
- SwiftZilla: https://swiftzilla.dev
- Swift Evolution: https://github.com/apple/swift-evolution
- SE-0412: 全局变量的严格并发
- SE-0471: 串行执行器隔离检查
- SE-0430: 参数传递
- SE-0414: 基于区域的隔离
- Apple Docs: https://developer.apple.com/documentation/swift/concurrency
- SwiftZilla: https://swiftzilla.dev
For More Information
更多信息
Each reference file contains detailed information, code examples, and best practices for specific topics. Visit https://swiftzilla.dev for comprehensive Swift concurrency documentation.
每个参考文件都包含特定主题的详细信息、代码示例和最佳实践。访问https://swiftzilla.dev获取完整的Swift并发编程文档。