NEW: Learn SwiftUI with my free YouTube video series! >>

< How to use @ObjectBinding to create object bindings   Working with lists >

How to use @EnvironmentObject to share data between views

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 @ObjectBinding 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 a bindable object that stores user settings:

class UserSettings: BindableObject {
    var didChange = PassthroughSubject<Void, Never>()

    var score = 0 {
        didSet {
            didChange.send(())
        }
    }
}

Yes, it only stores one value, but that’s OK – what matters is that when the value changes the PassthroughSubject tells all views using it to refresh.

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 these two lines of code inside the scene(_:willConnectTo:options:) method:

let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: ContentView())

It’s that second line of code 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.

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

< How to use @ObjectBinding to create object bindings   Working with lists >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.5/5

Click here to visit the Hacking with Swift store >>