2

is it possible to access enviromentObject variable inside the init function in a struct?

@EnvironmentObject var socketHandler: SocketHandler


init() {

    print(self.socketHandler.testVar)

}

I tried like this but did not get it to work. I got this error:

Fatal error: No ObservableObject of type SocketHandler found

I have added the enviromentObject to SceneDelegate and can access the variable in my UI.

1 Answers1

1

If you call it in a usual way, like

let contentView = ContentView().environmentObject(SomeObject())

then definitely the answer is NO, because here is what actually done:

let temp = ContentView() // < called constructor
let contentView = temp.environmentObject(SomeObject()) // call function on variable that 
                                               // just return another different value
Asperi
  • 228,894
  • 20
  • 464
  • 690