@EnvironmentObject in Views May Not be a Good Idea But Avoiding Them is Probably Much Worse

Mohammad Azam
4 min readJun 30, 2022
Photo by Sean Pollock on Unsplash

In SwiftUI, @EnvironmentObject allows you to create global state that can be shared and manipulated from any view in your application. We tend to put @EnvironmentObject in our views and directly access the global state. This creates a tight coupling between the view and the @EnvironmentObject, but avoiding this approach opens up a whole new cans of worms. In this article, I will discuss how @EnvironmentObject can be used in a SwiftUI view and how avoiding can create dependency injection nightmare.

EnvironmentObject Counter Example:

Let’s create a simple counter example. Our app will consists of three views. The ContentView will be the parent view, which will host IncrementCounterView and DisplayCounterView. IncrementCounterView will increment the global state counter value and DisplayCounterView will display the value from the global state.

The global state class AppState is shown below:

--

--

Mohammad Azam

Lead instructor at a coding bootcamp. Top iOS mobile instructor on Udemy. Author of multiple books and international speaker. azamsharp.school