Apologies for the lack of code syntax highlighting. I have plans to migrate my whole blog at some point in the future but I needed to get this out of my head before that.
I woke up this morning with several questions in my head and I couldn't find an existing blog post that answered one. If one does exist let me know I'd love to compare notes.
- How does the SwiftUI Environment work?
- Can it be used outside SwiftUI for more general dependency injection?
- If not how similar can I make something to do the job?
- Why do people keep telling me the Environment is unsafe and will crash if the object requested hasn't been added?
By early evening I think I had the answers. By night the blog was written and by the early hours the Swift Package was published.
[Update 17th Feb 2021 - Follow up post now available with information about the Swift Package status.]
[Update 20th Feb 2021 - Package 1.0.0 released.]
Spoiler 1 - I Know Property Wrappers
I now have enough understanding of property wrappers to understand much but not all of what the SwiftUI environment is doing.
I didn't know Property Wrappers before this morning, beyond the concept and use of existing ones. I'm now much more familiar with them including the future extension from the Evolution proposal that seems to be live in Swift and it seems is the basis for the @Environment and @Published property wrappers.
Spoiler 2 - No it can't be used for DI but...