@EnvironmentObject
declare an environment object
// 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 { ... }
}Last updated