我是 Swift 并發的新手(就像大多數人一樣,我想),我遇到了一個編譯器錯誤,我不知道該怎么辦。
struct Thing {
var counter = 0
mutating func increment() async {
counter = 1
}
}
class Controller: UIViewController {
var thing = Thing()
func mutate() async {
await thing.increment()
print(thing.counter)
}
}
let c = Controller()
Task {
await c.mutate()
}
該mutate()函式的第一行給了我以下錯誤。
Actor-isolated property 'thing' cannot be passed 'inout' to 'async' function call
如果我只是繼承class而不是UIViewController正常作業,但我需要這里的控制器,所以我需要弄清楚如何在特定的背景關系中使其作業。
uj5u.com熱心網友回復:
我認為問題出Thing在一個struct. 結構上的mutatingfunc 將為. 為了使它起作用,被視為呼叫中的引數。thingControllerthinginoutthing.increment()
如果您將事物actor設定為 a 而不是 astruct則increment()不需要是 a mutating func,因此thing不會被視為inout引數。
一種可能的解決方法是首先制作結構的副本,然后在副本上呼叫變異函式,然后將其存盤回控制器中的屬性中。
func mutate() async {
var thing = self.thing
await thing.increment()
self.thing = thing
print(thing.counter)
}
這是一個問題的原因是 UIViewControllers 現在都是演員,所以屬性被認為是演員隔離的。有一個nonisolated關鍵字,但它不能應用于存盤的屬性,所以它在這里似乎沒有幫助。
如果控制器更改為actor,則錯誤訊息會有所變化以說明這一點。
error: cannot call mutating async function 'increment()' on actor-isolated property 'thing'
await thing.increment()
^
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415470.html
標籤:
上一篇:Swift:添加負數
