@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.
Use ObservableObject to declare an observable object type.
Use @Published to declare published values in an observable object type.
Use @StateObject to initialize an observable object.
Use .environmentObject(_:) to put the model object in the environment.
Use
@EnvironmentObjectto 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.
Combine ⟩ ObservableObject (protocol)
SwiftUI ⟩ Model data ⟩ @ObservedObject (property wrapper)
Last updated
Was this helpful?