参与者的关闭:发送“不可发送”的风险会导致数据争用

问题描述 投票:0回答:1

为什么 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 actor swift-concurrency swift6 xcode16
1个回答
0
投票

正如您所注意到的,在 Swift 6(在 Xcode 16 beta 3 中)中,您将收到代码警告:

sendable warning

但是,影响其隔离区域的是

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) { }
}

no sendable warning

有关更多信息,请参阅 SE-0414 – 基于区域的隔离

© www.soinside.com 2019 - 2024. All rights reserved.