为什么 Swift 6 (Xcode 16 Beta 3) 不允许这样做?
class NonSendable { }
actor MyActor {
func foo() {
let nonSendable = NonSendable()
for _ in 1...3 {
// ✅ Compiles fine
bar(nonSendable)
}
(1...3).forEach { _ in
// ❌ Sending 'nonSendable' risks causing data races
// 'self'-isolated 'nonSendable' is captured by a actor-isolated
// closure. actor-isolated uses in closure may race against later
// nonisolated uses
bar(nonSendable)
}
}
func bar(_: NonSendable) { }
}
正如您所注意到的,在 Swift 6(在 Xcode 16 beta 3 中)中,您将收到代码警告:
但是,影响其隔离区域的是
nonSendable
-for
循环中对 in
的引用的存在。例如,删除该引用,错误就会消失:
actor MyActor {
func foo() {
let nonSendable = NonSendable()
// for _ in 1...3 {
// bar(nonSendable)
// }
(1...3).forEach { _ in
// ✅ Compiles fine
bar(nonSendable)
}
}
func bar(_ object: NonSendable) { }
}
有关更多信息,请参阅 SE-0414 – 基于区域的隔离。