Environmental Issues In SwiftUI

When is a descendant view not a descendent view?

Michael Long
The Swift Cooperative

--

SwiftUI Environment Tree generated by DALL-E

I’ve been working on a project for the past few weeks that makes heavy use of custom SwiftUI Environment variables.

And during development I ran across a bug that, in hindsight, wasn’t really a bug at all. But until I tracked it down and figured out why, the behavior was somewhat unexpected.

And at odds with my mental model of how SwiftUI worked and how environment information propagated throughout the code.

So enough of that. Let me explain the problem, the misconception, and, of course, the solution.

Descendant Views

You’re no doubt familiar with SwiftUI’s .environment modifier and how it can be used to alter the environment of descendant views. It says so right on the label and in Apple’s documentation.

But what qualifies as a descendant view?

Let’s look at some code.

Defining Our Variable

For the sake of this discussion, let’s create a simple environment variable that’s used to manage a single color for our application. For that we need to define a newEnvironmentKey and extend EnviromentValues.

struct MyColorKey: EnvironmentKey {…

--

--

Michael Long
The Swift Cooperative

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.