๐Ÿ”ธenvironment object

SwiftUI โŸฉ view โŸฉ environment โŸฉ object

An environment object is a state object, which is

  1. initialized in an ancester view by adding a @StateObject property

  2. and put in the environment by calling the ancester view's .environmentObject(_:) modifier.

To use an environment object In a subview, declare a corrspoinding @EnvironmentObject property in the subview.

// app
struct MyApp: App {
    
    // โญ๏ธ 1. declare & initialize a state object
    @StateObject private var data = ModelData() 
    
    var body: some Scene {
        WindowGroup {
            RootView()
                // โญ๏ธ 2. put an environment object.
                .environmentObject(data)         
        }
    }
}

// Subview: RootView's subview
struct Subview: View {

    // โญ๏ธ get the environment object.
    @EnvironmentObject var data: ModelData      
    
    var body: some View { ... }
}

Be sure to set a corresponding model instance on an ancester view by calling its .environmentObject(_:) modifier.

Last updated