UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How to initialize @StateObject in initializer

Forums > SwiftUI

Having watched Paul's latest birthday video, I've vowed to use @StateObject properly, which of course lands me in trouble almost immediately:

@main
struct ArkansasApp: App {
    @StateObject var appState = AppState()
    @StateObject var arkansasScene: ArkansasScene

    init() {
    // Problem here: compiler says "Escaping autoclosure captures mutating 'self' parameter"
    // I'm only barely grasping what the message means, so naturally I have no idea what to
    // do to fix it.
        _arkansasScene = StateObject(wrappedValue: ArkansasScene(appState: _appState))
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appState)
                .environmentObject(arkansasScene)
        }
    }
}

I was doing this with @ObservedObject before, and it was working fine, but I'm kind of fussy about doing things the right way, plus Paul says it might not always behave properly at runtime. Anyone have any advice?

3      

Try to initialize the appState also in your initializer.

4      

_appState refers to the @StateObject property wrapper. Maybe you mean appState, which refers to the wrapped value? I don't know what the initializer for ArkansasScene looks like.

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.