Logo for tanaschita.com

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:

  1. Declaring a new environment key type:
private struct AnalyticsCategoryEnvironmentKey: EnvironmentKey {
static let defaultValue: String = "none"
}
Sponsorship logo
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
  1. Defining our environment value property by extending EnvironmentValues:
extension EnvironmentValues {
var analyticsCategory: String {
get { self[AnalyticsCategoryEnvironmentKey.self] }
set { self[AnalyticsCategoryEnvironmentKey.self] = newValue }
}
}
  1. 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: String
var body: some View {
Text(analyticsCategory)
}
}

Instead of a String, we can of course use any other type for the environment value.

Sponsorship logo
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

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swiftui

swift

ios

Understanding basic animations in SwiftUI

Learn different options to animate SwiftUI views.

16 Jan 2023 · 4 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum