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))
}
}
Environment object is injected after init, so we should update state later, most often it is used
onAppear
:as alternate it can be used subview, by same approach like in https://stackoverflow.com/a/59368169/12299030