@EnvironmentObject

declare an environment object

SwiftUI โŸฉ Data Flow โŸฉ @EnvironmentObject

The @EnvironmentObject property wrapper is used to declare (in a subview) an environment object property provided by an ancester view.

// app
struct MyApp: App {
    
    // โญ๏ธ 1. initialize a state object (as the app's model data)
    @StateObject private var modelData = ModelData() 
    
    var body: some Scene {
        WindowGroup {
            RootView()
                // โญ๏ธ 2. put the model object in the environment.
                .environmentObject(modelData)         
        }
    }
}

// assume Subview is a subview of RootView in the view hierarchy
struct Subview: View {

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

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

Last updated