我正在尝试将 aStateObject
actor
的初始化程序放在 aasync
中App
,但我找不到这样做的方法。
假设我有这个演员:
actor Foo: ObservableObject {
init() async {
// ...
}
}
这导致名义上的错误:
import SwiftUI
struct MyApp: App {
@StateObject
var foo = await Foo() // 'async' call cannot occur in a property initializer
var body: some Scene {
// ...
}
}
这会导致类似的错误:
import SwiftUI
struct MyApp: App {
@StateObject
var foo: Foo
init() async {
_foo = .init(wrappedValue: await Foo()) // 'async' call in a function that does not support concurrency
}
var body: some Scene {
// ...
}
}
甚至这些也行不通:
import SwiftUI
struct MyApp: App {
@StateObject
var foo: Foo
init() async {
Task {
self._foo = .init(wrappedValue: await Foo()) // Mutation of captured parameter 'self' in concurrently-executing code
}
}
var body: some Scene {
// ...
}
}
import SwiftUI
struct MyApp: App {
@StateObject
var foo: Foo
init() async {
Task { [self] in
self._foo = .init(wrappedValue: await Foo()) // Cannot assign to property: 'self' is an immutable capture
}
}
var body: some Scene {
// ...
}
}
看来无论我做什么,我都不能Foo
成为MyApp
. 我在这里想念什么?这当然是可能的。
我在使用 SwiftUI 时也遇到了同样的问题View
,所以任何适用于View
s 和App
s 的建议都会非常棒!