SwiftUI EnvironmentObject Tutorial

@EnvironmentObject can be used to share data between all views and to auto-update those views when the data changes In this tutorial a property is created and shared between views . SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIEnvironmentObjectTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

Go to the ContentView.swift file and add the following class to the file

class GameSettings: ObservableObject {
    @Published var score: Int = 0

Go to the SceneDelegate.swift file and add the following property

var settings = GameSettings()

Add the settings property as a parameter to the environmentObject function of the contentView.

if let windowScene = scene as? UIWindowScene {
  let window = UIWindow(windowScene: windowScene)
  window.rootViewController = UIHostingController(rootView: contentView.environmentObject(settings))
  self.window = window

Go back to the ContentView.swift file. In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

Change the code inside the ContentView struct to

struct ContentView: View {
    // 1.
    @EnvironmentObject var settings: GameSettings
    var body: some View {
        NavigationView {
            VStack {
                // 2.       
                Stepper(value: $settings.score, in: 1...1000000, step: 1000,  label: {
                    Text("Current Score:  \(settings.score)")
                // 3.
                NavigationLink(destination: ScoreView()) {
                    Text("Show Current Score")
  1. The EnvironmentObject property watches and updates the settings value.

  2. A stepper is displayed which can be used to change the score.

  3. The scoreView( ) struct will be called to show the current score.

Add the scoreView struct.

struct ScoreView: View {
    @EnvironmentObject var settings: GameSettings
    var body: some View {
        Text("Score: \(settings.score)")

The ScoreView will display the current score. Go to the preview, and click the Live mode button. Change the score with the stepper and click the “Show current score” text. The score value is also updated in the ScoreView.

The preview will look like this.

The source code of the SwiftUITutorial can be downloaded at the ioscreator repository on Github.