Passing Data in SwiftUI via the View’s Environment

Learn how to access and share data using @EnvironmentObject, @Published, the ObservableObject protocol, and the .environmentObject(_:) modifier, among multiple views in SwiftUI.

Passing Data in SwiftUI via the View’s Environment

In SwiftUI apps with multiple views, you often need to share data among them. If you've been developing apps for iOS/iPadOS using UIKit you might be wondering how to do this in SwiftUI. Anyway, if you're a beginner, you won't have any problems following this tutorial: no previous knowledge of UIKit is required.

Using SwiftUI's @EnvironmentObject property wrapper, we can share data between many views in an app. By doing so, we can share model data anywhere it's needed while ensuring that our views are refreshed when the model data is updated.

This tutorial is the third of a series that explores 4 different solutions for passing data between views:

Last time we explored how to pass data using a property from a primary to a secondary view using hierarchical navigation. This time we are going to share the same object with multiple views.

Become a free member or log in to proceed.