示例工程 21-actors-isolation
21-actors-isolation/Tests/Ch21KitTests/ActorTests.swift
import Testing
@testable import Ch21Kit
@Suite("actor 隔离")
struct ActorTests {
@Test func concurrentIncrementsAreSerialized() async {
let counter = Counter()
await withTaskGroup(of: Void.self) { group in
for _ in 0..<20 {
group.addTask {
await counter.increment()
}
}
}
#expect(await counter.count == 20)
}
@Test func nonisolatedMemberNeedsNoAwait() {
let counter = Counter(id: 9)
#expect(counter.label() == "counter-9")
#expect(counter.id == 9)
}
@Test func isolatedStateRequiresAwait() async {
let counter = Counter()
await counter.add(5)
let count = await counter.count
#expect(count == 5)
}
}