NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to use @EnvironmentObject to share data between views

Paul Hudson    @twostraws   

Updated for Xcode 12.0

For data that should be shared with all views in your entire app, SwiftUI gives us @EnvironmentObject. This lets us share model data anywhere it’s needed, while also ensuring that our views automatically stay updated when that data changes.

Think of @EnvironmentObject as a smarter, simpler way of using @ObservedObject on lots of views. Rather than creating some data in view A, then passing it to view B, then view C, then view D before finally using it, you can create it in view and put it into the environment so that views B, C, and D will automatically have access to it.

Note: Environment objects must be supplied by an ancestor view – if SwiftUI can’t find an environment object of the correct type you’ll get a crash. This applies for previews too, so be careful.

As an example, here’s an observable object that stores user settings:

class UserSettings: ObservableObject {
    @Published var score = 0

Yes, it only stores one value, but that’s OK – what matters is that when the value changes the @Published property wrapper will ensure all views using it are refreshed.

User settings are a sensible piece of data that we might want to share everywhere in our app, so that we no longer need to handle synchronizing it by hand.

So, when our app first launches we’re going to create an instance of UserSettings so that shared instance is accessible everywhere in our app.

If you open SceneDelegate.swift you’ll find this line of code inside the scene(_:willConnectTo:options:) method:

window.rootViewController = UIHostingController(rootView: ContentView())

That creates our initial content view and presents it on the screen. This is where we need to pass in any environment objects that we’ve created, so that SwiftUI can make them available inside ContentView but also any other views it uses.

First, add this as a property of your SceneDelegate:

var settings = UserSettings() 

That creates a settings instance once, and stores it safely. Now go back down to those two lines of code I showed you and change the second line so it passes our settings property into ContentView as an environment object, like this:

window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(settings))

Once that’s done, the shared UserSettings instance is available to our content view and any other views it hosts or presents. All you need to do is create a property using the @EnvironmentObject property wrapper, like this:

@EnvironmentObject var settings: UserSettings

That doesn’t need to be initialized with a default value, because it will automatically be read from the environment.

So, we could make a ContentView struct that increments our score setting, and even make it present a DetailView that shows the score setting, all without needing to create or pass around any local instances of UserSettings – it always just uses the environment.

Here’s the code to make that happen:

struct ContentView: View {
    @EnvironmentObject var settings: UserSettings

    var body: some View {
        NavigationView {
            VStack {
                // A button that writes to the environment settings
                Button(action: {
                    self.settings.score += 1
                }) {
                    Text("Increase Score")

                NavigationLink(destination: DetailView()) {
                    Text("Show Detail View")

struct DetailView: View {
    @EnvironmentObject var settings: UserSettings

    var body: some View {
        // A text view that reads from the environment settings
        Text("Score: \(settings.score)")

So, once you’ve injected an object into the environment you can start using it immediately either in your top-level view or ten levels down – it doesn’t matter. And most importantly, whenever any view changes the environment, all views relying on it are automatically refreshed so they stay in sync.

As you can see, we didn’t need to explicitly associate the UserSettings instance in our scene delegate with the settings property in our two views – SwiftUI automatically figured out that it has a UserSettings instance in the environment, so that’s the one that gets used.

Warning: Now that our views rely on an environment object being present, it’s important that you also update your preview code to provide some example settings to use. For example, using something like ContentView().environmentObject(UserSettings()) for your preview ought to do it.

Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.4/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.