🔸environment object
SwiftUI ⟩ view ⟩ environment ⟩ object
An environment object is a state object, which is
initialized in an ancester view by adding a @StateObject property
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.
ObservableObject:declare an observable object type.
@Published:declare published values in an observable object type.
@StateObject:initialize an observable object.
Use .environmentObject(_:) to put the model object in the environment.
Use @EnvironmentObject to declare an observable object property provided by an ancestor view.
observer: any view or object that uses the observable object's data.
data model:data shared with any views in your app.
Last updated
Was this helpful?