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 customObservableObjectinjected 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: