SALE ENDS TODAY: Save 50% on all Swift books and bundles! >>

How to use @EnvironmentObject to share data between views

Paul Hudson    @twostraws   

Fully updated for Xcode 11.2

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.

SPONSORED Instabug helps you identify and resolve severe crashes quickly. You can retrace in-app events and know exactly which line of code caused the crash along with environment details, network logs, repro steps, and the session profiler. Ask more questions or keep users up-to-date with in-app replies straight from your dashboard. Instabug takes data privacy seriously, so no one sees your data but you! See more detailed features comparison and try Instabug's crash reporting SDK for free.

Save 50% on all books and bundles

The biggest ever Hacking with Swift sale is now on, letting you save 50% on all books and bundles. Learn something new with Swift and enjoy great savings while the sale lasts!

Click here to save 50% in our Black Friday sale!

Similar solutions…

BUY OUR BOOKS
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.5/5