@EnvironmentObject lets different parts of your app share data easily without passing it around manually. It helps keep your app organized and your code clean.
@EnvironmentObject for shared state in iOS Swift
class SharedData: ObservableObject { @Published var count = 0 } struct ContentView: View { @EnvironmentObject var data: SharedData var body: some View { Text("Count: \(data.count)") } }
@EnvironmentObject is used inside a view to access shared data.
The shared data class must conform to ObservableObject and use @Published for properties that change.
class UserSettings: ObservableObject { @Published var username = "Guest" } struct ProfileView: View { @EnvironmentObject var settings: UserSettings var body: some View { Text("Hello, \(settings.username)!") } }
struct CounterView: View {
@EnvironmentObject var sharedData: SharedData
var body: some View {
Button("Increment") {
sharedData.count += 1
}
}
}This app shows a number and a button. When you tap the button, the number increases. The number is stored in shared data accessed with @EnvironmentObject. This way, if you add more views, they can also see and change the number easily.
import SwiftUI class SharedData: ObservableObject { @Published var count = 0 } struct ContentView: View { @EnvironmentObject var data: SharedData var body: some View { VStack(spacing: 20) { Text("Count: \(data.count)") .font(.largeTitle) Button("Increment") { data.count += 1 } .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } .padding() } } @main struct MyApp: App { @StateObject private var sharedData = SharedData() var body: some Scene { WindowGroup { ContentView() .environmentObject(sharedData) } } }
Remember to provide the shared object with .environmentObject() at the app root or parent view.
If a view uses @EnvironmentObject but the object is not provided, the app will crash.
Use @Published to mark properties that should update the UI when changed.
@EnvironmentObject shares data easily across many views.
It works with classes conforming to ObservableObject and @Published properties.
Always inject the shared object with .environmentObject() in your app.