SwiftUI EnvironmentObject

In SwiftUI, @EnvironmentObject is a property wrapper that we use to share data between many views.

EnvironmentObject vs ObservedObject

Let’s say, we have 3 views named View1, View2 and View3. View1 contains View2 and View2 contains View3. Using EnvironmentObject, we can pass data from View1 to View3. But if we use ObservedObject, we have to first pass data to View2 and then pass it to View3.

EnvironmentObject Example

Let’s see with an example. In the example, we have 3 views named BlackView, BlueView and GreenView. BlackView contains BlueView and BlueView contains GreenView.

  • NumberManager is the class that we will share its instance between views, it conforms to ObservableObject and its number property has @Published property wrapper.
  • BlackView has NumberManager instance inside and it sends this data with environmentObject() modifier.
  • BlueView and GreenView expects to get a NumberManager object in the environment. See that BlueView does not send this data, it is already provided by BlackView.

When we tap on the button in BlackView, text in all the views updated with same data:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store