How to use EnvironmentObject to initialize State Property in SwiftUI?

Viewed 1361

I am having a small Issue with initializing a State with Data from an EnvironmentObject.

@EnvironmentObject var settings: Settings
    
@State var localAllowReminders: Bool
    
init() {
    self._localAllowReminders = State(initialValue: settings.allowReminders)
}

Obviously, I get the following Error Message: 'self' used before all stored properties are initialized.

Question: How can I initialize a State with Data out of a EnvironmentObject?

Thanks for your help.

1 Answers

EnvironmentObject is injected after view constructor call, so you have to initialize state to some default and reset it to desired value in top body view onAppear modifier, like

@EnvironmentObject var settings: Settings
@State var localAllowReminders: Bool = false   // << just any default
    
var body: some View {
    VStack {       // << any top view
        // ...
    }
    .onAppear {
       self.localAllowReminders = settings.allowReminders   // << here !!
    }
}
Related