0

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))
  }
}
nedwin
  • 1

1 Answers1

-1

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

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 1
    I considered the onAppear hack, but it's not sufficient. The *view* needs the state, specifically the array length, initially to be properly rendered. The array length can't vary between the initial render and after onAppear because it will cause an out of bounds exception. – nedwin Nov 24 '20 at 17:55