How to create custom @Environment values in SwiftUI
Learn how to create custom environment values by extending the EnvironmentValues structure
12 Mar 2021 · 2 min read
With the @Environment property wrapper, we have the possibility to share data between SwiftUI views without explicitly passing the data from view to view.
Besides using the predefined values provided by SwiftUI, we can also create our own custom @Environment values using the following 3 steps:
- Declaring a new environment key type:
private struct AnalyticsCategoryEnvironmentKey: EnvironmentKey {static let defaultValue: String = "none"}

Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE
- Defining our environment value property by extending EnvironmentValues:
extension EnvironmentValues {var analyticsCategory: String {get { self[AnalyticsCategoryEnvironmentKey.self] }set { self[AnalyticsCategoryEnvironmentKey.self] = newValue }}}
- Now we can use the environment value in our views.
// Setting the environment value.LoginView().environment(\.analyticsCategory, "login")// Accessing the environment value.struct LoginView: View {@Environment(\.analyticsCategory) var analyticsCategory: Stringvar body: some View {Text(analyticsCategory)}}
Instead of a String, we can of course use any other type for the environment value.

Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE
Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips