christophriepe
christophriepe

Reputation: 1673

How to use EnvironmentObject to initialize State Property in SwiftUI?

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.

Upvotes: 13

Views: 5033

Answers (1)

Asperi
Asperi

Reputation: 257819

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 !!
    }
}

Upvotes: 11

Related Questions