SwiftUIMidMCQ

What is the difference between `@Environment` and `@EnvironmentObject`?

Test your knowledge:

Explanation & Code

Answer: Both inject values from the environment, but they serve different purposes.

  • @Environment — reads system or built-in values (color scheme, locale, font, dismiss action)
  • @EnvironmentObject — reads a custom ObservableObject injected by a parent view

Code Example:

// @Environment — built-in system values
struct ThemeAwareView: View {
    @Environment(\.colorScheme) var colorScheme
    @Environment(\.dismiss) var dismiss

    var body: some View {
        Text(colorScheme == .dark ? "Dark mode" : "Light mode")
        Button("Close") { dismiss() }
    }
}

// @EnvironmentObject — custom shared object
class AppSettings: ObservableObject {
    @Published var fontSize: CGFloat = 16
}

struct ChildView: View {
    @EnvironmentObject var settings: AppSettings

    var body: some View {
        Text("Hello").font(.system(size: settings.fontSize))
    }
}

// Must be injected by a parent
ContentView()
    .environmentObject(AppSettings())

Rate your understanding:

Ready to practice more SwiftUI?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.