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"
  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.
.environment(\.analyticsCategory, "login")
// Accessing the environment value.
struct LoginView: View {
@Environment(\.analyticsCategory) var analyticsCategory: String
var body: some View {

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

Related tags

Written by