How to create custom @Environment values in SwiftUI
Learn how to share data between SwiftUI views without passing the data explicitly.
27 May 2024 · 4 min read
The @Environment property wrapper in SwiftUI allows us to share data between views without explicitly passing the data from view to view.
While SwiftUI provides many built-in environment values, there are times when we need to create custom ones to suit our specific needs.
Let's directly jump in and see how to do that.

To create a custom @Environment value, we need to:
- Declare a new EnvironmentKey type.
- Extend the EnvironmentValues structure to include a property for our new custom key.
- Use the @Environment property wrapper to inject the custom value into our views.
Let's look at each step in more detail.
As an example, we'll create a custom environment value to manage the theme of our iOS app. The theme includes properties like colors and font sizes that can be accessed throughout the app.
1. Declaring a new EnvironmentKey type
At first, we create a new type that conforms to the EnvironmentKey protocol. For example:
private struct ThemeEnvironmentKey: EnvironmentKey {static let defaultValue: Theme = Theme.default}
2. Extending the EnvironmentValues structure
Next, we extend the EnvironmentValues structure to include a property for our custom environment key. This makes it accessible via the environment.
extension EnvironmentValues {var theme: Theme {get { self[ThemeEnvironmentKey.self] }set { self[ThemeEnvironmentKey.self] = newValue }}}
3. Using the @Environment property wrapper
Now that we have defined a custom environment value, we can use it in our views with the @Environment property wrapper.
// Setting the environment value.LoginView().environment(\.theme, Theme.default)// Accessing the environment value.struct LoginView: View {@Environment(\.theme) var theme: Themevar body: some View {Text("Hello").foregroundColor(theme.primary)}}
Instead of a String, we can of course use any other type for the environment value.



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



