The @Environment property wrapper in SwiftUI

Learn how to share global data between SwiftUI views

12 Mar 2021 · 2 min read

With the @Environment property wrapper, SwiftUI provides a possibility to share data between views without explicitly passing the data from view to view. By setting an environment property on a view, it will be available not only in the view itself but also in all of it's subviews.

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 in our view by using the colorScheme property.

struct ContentView: View {
@Environment(\.colorScheme) private var colorScheme
var body: some View {
VStack {
Text(colorScheme == .dark ? "dark" : "light")
}
}
}

A full list is available at Apple's EnvironmentValues documentation.

If you like to create your own @Environmentvalues, check out this article on How to create custom @Environment values in SwiftUI.