SwiftUI and the Missing Environment Object

Using ViewModifiers to fix another major issue in SwiftUI development.

Michael Long
The Startup
Published in
6 min readOct 7, 2019

--

SwiftUI provides us with a quick and easy way to pass models and services down the View hierarchy, the EnvironmentObject.

Just add your model or service to your view as an environmentObject view modifier, and any child view that’s interested can use an EnvironmentObject property wrapper to grab it and use it as they see fit.

It’s a fundamental architectural building block for SwiftUI and it works amazingly well… except when it doesn’t.

Updated for Xcode 12 and iOS 14

It appears that the EnvironmentObject crash described below no longer occurs when building with Xcode 12, Swift 5.3, and when running on iOS 14.

That said, it appears that certain Environment settings are still not propagating properly either. For example, setting the accentColor in the application root doesn’t appear to affect the accentColor in a view presented later on.

The method described in this article fixes both issues, not to mention being generally useful in its own right.

An EnvironmentObject example

--

--

Michael Long
The Startup

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.