Actor

版本新特性 / Swift 5.5

// *** 以前 ***
final class CounterOld {
    private let queue = DispatchQueue(label: "counter")
    private var value = 0

    func increment() { queue.sync { value += 1 } }
    var current: Int { queue.sync { value } }
    // 没有任何机制检查每条路径都经过队列:之后多加一次直接读取,竞争就又回来了
}

// *** 在 5.5 版本中 ***
actor Counter {
    private var value = 0

    func increment() { value += 1 }      // 在 actor 内部无需 await
    var current: Int { value }
}

let counter = Counter()
await counter.increment()
print(await counter.current)

// 编译器自己禁止不带 await 从外部访问 actor 的状态,
// 因此保护不会被遗忘。
// 不触碰 actor 任何内容的方法标记为 nonisolated