示例工程 21-actors-isolation
21-actors-isolation/Sources/Ch21Kit/Actors.swift
/// actor 保护自己的可变状态:跨隔离访问必须 await。
public actor Counter {
public nonisolated let id: Int
public private(set) var count = 0
public init(id: Int = 1) {
self.id = id
}
public func increment() {
count += 1
}
public func add(_ amount: Int) {
count += amount
}
/// `nonisolated`:不访问隔离状态,可以直接调用,不需要 await。
public nonisolated func label() -> String {
"counter-\(id)"
}
}
/// 重入陷阱:检查与修改之间隔着 await,另一个任务可以插入。
public actor BankAccount {
public private(set) var balance: Int
public init(balance: Int) {
self.balance = balance
}
/// 不安全:`await` 期间 actor 会处理其他消息,余额可能已变化。
public func withdrawUnsafe(_ amount: Int, delay: Duration) async -> Bool {
guard balance >= amount else { return false }
try? await Task.sleep(for: delay)
balance -= amount
return true
}
/// 安全:先扣款,再执行需要等待的通知/日志。
public func withdrawSafe(_ amount: Int, delay: Duration) async -> Bool {
guard balance >= amount else { return false }
balance -= amount
try? await Task.sleep(for: delay)
return true
}
}
/// `@MainActor` 是主线程隔离域:成员默认在主 actor 上执行。
@MainActor
public final class ViewModel {
public private(set) var title = ""
public private(set) var updates = 0
public init() {}
public func loadTitle() -> String {
title = "loaded"
updates += 1
return title
}
}