0
0
iOS Swiftmobile~5 mins

@EnvironmentObject for shared state in iOS Swift

Choose your learning style9 modes available
Introduction

@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.

When you want multiple views to read and update the same data.
When you have a user profile or settings that many screens need access to.
When you want to avoid passing data through many layers of views.
When you want your app to update UI automatically when shared data changes.
Syntax
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.

Examples
Access a shared username from anywhere in the app.
iOS Swift
class UserSettings: ObservableObject {
  @Published var username = "Guest"
}

struct ProfileView: View {
  @EnvironmentObject var settings: UserSettings
  var body: some View {
    Text("Hello, \(settings.username)!")
  }
}
Update shared data from a button tap.
iOS Swift
struct CounterView: View {
  @EnvironmentObject var sharedData: SharedData
  var body: some View {
    Button("Increment") {
      sharedData.count += 1
    }
  }
}
Sample App

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.

iOS Swift
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)
    }
  }
}
OutputSuccess
Important Notes

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.

Summary

@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.