create custom environmentvalues in swiftui in swift

In SwiftUI, we can create custom environment values using the EnvironmentValues struct.

First, we define our custom environment value as a Key:

main.swift
struct MyCustomEnvironmentKey: EnvironmentKey {
    static let defaultValue = "default value"
}

extension EnvironmentValues {
    var myCustomEnvironmentValue: String {
        get { self[MyCustomEnvironmentKey.self] }
        set { self[MyCustomEnvironmentKey.self] = newValue }
    }
}
289 chars
11 lines

Here, we've created a custom environment key called MyCustomEnvironmentKey, which has a default value of "default value". We then extend EnvironmentValues to add a computed property myCustomEnvironmentValue that gets and sets the value associated with our custom key.

Now we can use the custom environment value in any SwiftUI view:

main.swift
struct MyView: View {
    @Environment(\.myCustomEnvironmentValue) private var myValue
    
    var body: some View {
        Text(myValue)
    }
}
148 chars
8 lines

Here, we use the @Environment property wrapper to get the value associated with our custom environment key myCustomEnvironmentValue. Note that we must mark the property as private to avoid accidentally modifying the value associated with the wrong environment key.

We can also set the value of our custom environment value for a specific view hierarchy by using the .environment modifier:

main.swift
MyView()
    .environment(\.myCustomEnvironmentValue, "custom value")
70 chars
3 lines

Now, the myValue property in MyView will return "custom value" instead of the default value of "default value".

related categories

gistlibby LogSnag