|
Why am I unable to use an EnvironmentObject var in the init of a View? When I try my app says "No ObservableObject of type ??? found". However, I am able to use the var anywhere else in the View, e.g. in a button's tap event. This does not work:
But this does work:
If I try to call loadList from init, it will give the error. But if I call loadList from a tap event it will work correctly. This seems like the View doesn't have access to the EnvironmentObject at initialisation time. Am I doing something wrong? |
|
The environment is passed down when the |
|
|
|
I just need to thank you for making this topic: I've been tearing my hair out for hours trying to understand why (seemingly) NONE of my child Views were inheriting or able to access an object I placed in the environment. I tried debugging by testing access to the environment within each View's init(), because that seems safe, right? Not at all. Finally your topic helped me understand what's happening. I have no idea why this behavior exists. Is there any place in Apple's documentation that explains why (or even that at all it occurs) Views cannot access environment objects during their init() phase? |
|
Because when |
|
@roosterboy, thank you for explaning! I wish this were made more clear somewhere within Apple's own documentation. Despite understanding why this happens, I now find myself needing to come up with hack-y (and, in my mind, distinctly non-Swift-y) workarounds for my use-case. I'm using Firestore to retrieve a specific document and display its details in a |
SPONSORED Ready to dive into the world of Swift? try! Swift Tokyo is the premier iOS developer conference will be happened in April 9th-11th, where you can learn from industry experts, connect with fellow developers, and explore the latest in Swift and iOS development. Don’t miss out on this opportunity to level up your skills and be part of the Swift community!
Sponsor Hacking with Swift and reach the world's largest Swift community!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.