Question about creating a @MainActor instance in SwiftUI

I have created a Store declared as @MainActor

@MainActor
class Store{
      var name = ""
}

Create an instance of it in code

@main
struct NewReduxTest2App: App {
    let store =  Store()
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

I got error: Call to main actor-isolated initializer 'init(initialState:environment:reducer:)' in a synchronous nonisolated context

If I replace the code with

@StateObject var store = Store()

The code can be executed correctly.
I don't understand why I have to use @StateObject to create this instance correctly.

1 Like

It's because @StateObject is already the main actor, but your NewReduxTest2App struct is not – try annotating NewReduxTest2App with @MainActor, or maybe just annotate your store property with @MainActor.

3 Likes

Thanks for your answer.After annotating NewReduxTestApp as @MainActor, I can use let to create instances of Store.
Is it understood that when I use @StateObject, the compiler will automatically infer that the view will run in the main actor.

Indeed, you're absolutely correct.

Happy to help!

2 Likes