转换不可发送的函数值可能会引入数据竞争。

15

我有一个简单的代码片段:

struct ContentView: View {
    var body: some View {
        Text("Hello world!")
            .task {
                await myAsyncFunc()
            }
    }

    private func myAsyncFunc() async {}
}

这段代码能够成功编译。然而,如果我用以下代码替换任务:
.task(myAsyncFunc)

代码无法运行,并提示以下错误:

将不可发送的函数值转换为“@Sendable() async -> Void”可能会引入数据竞争

为什么会出现这种情况,我该如何解决?

1个回答

13

正如它所述,函数可以标记为 @Sendable。这将用于防止数据竞争。

将其更改为以下内容:

@Sendable private func myAsyncFunc() async {}

注意:在访问修饰符之前必须使用@Sendable


1
Main actor-isolated synchronous instance method '<#method#>' cannot be marked as '@Sendable'; this is an error in Swift 6 - amq

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接