In SwiftUI, we can create custom environment values using the EnvironmentValues
struct.
First, we define our custom environment value as a Key
:
main.swift289 chars11 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.swift148 chars8 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.swift70 chars3 lines
Now, the myValue
property in MyView
will return "custom value"
instead of the default value of "default value"
.
gistlibby LogSnag