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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.