Error referencing EnvironmentObject in view initializer

127 Views Asked by At

I'm trying to reference an environment object in a SwiftUI view initializer to set up a state value, but I'm getting an error 'self' used before all stored properties are initialized. Is there a way to do this at all as you need to reference self to access the environment object? I feel like referencing an inherited value is something you should be able to do in a view's construction.

struct Example: View {
 
  @EnvironmentObject var object: Items
  @State var ints: Array<Int>
  
  init() {
    self._ints = State(initialValue: Array(repeating: 0, count: self.object.items.count))
  }
}
1

There are 1 best solutions below

1
On

Environment object is injected after init, so we should update state later, most often it is used onAppear:

struct Example: View {
 
  @EnvironmentObject var object: Items
  @State var ints = Array<Int>()         // << just empty
  
  var body: some View {
    Text("Some view here")
     .onAppear {
        self.ints = Array(repeating: 0, count: self.object.items.count)
     }
  }
}

as alternate it can be used subview, by same approach like in https://stackoverflow.com/a/59368169/12299030