I'm trying to place a StateObject
actor
whose initializer is async
in an App
, but I can't find a way to do that.
Let's say I have this actor:
actor Foo: ObservableObject {
init() async {
// ...
}
}
This results in the titular error:
import SwiftUI
struct MyApp: App {
@StateObject
var foo = await Foo() // 'async' call cannot occur in a property initializer
var body: some Scene {
// ...
}
}
This results in a similar error:
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 {
// ...
}
}
And even these won't work:
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 {
// ...
}
}
It seems no matter what I do, I cannot have a Foo
be a member of MyApp
. What am I missing here? Surely this is possible.
I run into the same problems with SwiftUI View
s too, so any advice that works for both View
s and App
s would be spectacular!