Understanding the @Environment property wrapper in SwiftUI
Learn different scenarios for using the @Environment property wrapper.
29 Jul 2024 · 3 min read
The @Environment property wrapper in SwiftUI allows data sharing between views without explicitly passing the data down the view hierarchy. Setting an environment property on a view makes it accessible to that view and all its subviews.
There are different scenarios for using the @Environment property wrapper:
- Using predefined @Environment values in SwiftUI
- Using custom @Environment values
- Using @Environment objects
Let's explore each scenario in more detail.

1. Using one of SwiftUI's predefined @Environment values
SwiftUI provides predefined values that we can use just out of the box like colorScheme, managedObjectContext, timeZone, openURL and more.
For example, we can access the current color scheme by using the colorScheme property:
struct ContentView: View {@Environment(\.colorScheme) private var colorSchemevar body: some View {VStack {Text(colorScheme == .dark ? "dark" : "light")}}}
2. Using custom @Environment values
While SwiftUI provides many built-in environment values, there are times when we need to create custom ones to suit our specific needs.
This involves creating an environment key, injecting the custom value into views, and using it similarly to predefined values:
@Environment(\.theme) private var theme
To learn more, check out this article on how to create custom @Environment values in SwiftUI.
3. Using @Environment objects
We can also pass reference objects between views using @Environment. For example:
@State private var viewModel = ViewModel()SomeView().environment(viewModel)
We can access it without using keys:
@Environment(ViewModel.self) private var viewModel
This method is useful for sharing complex objects that manage state or handle logic across multiple views. It ensures that all views are referencing the same instance, keeping the data consistent.



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



