๐Ÿ”ธenvironment object

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

// 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 { ... }
}

Last updated

Was this helpful?