Protocol¶
EnvironmentKey¶
A key for accessing values in the environment.¶
Declaration¶
protocol EnvironmentKey
Overview¶
You can create custom environment values by extending the EnvironmentValues structure with new properties. First declare a new environment key type and specify a value for the required defaultValue property:
private struct MyEnvironmentKey: EnvironmentKey {
static let defaultValue: String = "Default value"
}
extension EnvironmentValues {
var myCustomValue: String {
get { self[MyEnvironmentKey.self] }
set { self[MyEnvironmentKey.self] = newValue }
}
}
MyView()
.environment(\.myCustomValue, "Another string")
extension View {
func myCustomValue(\_ myCustomValue: String) -> some View {
environment(\.myCustomValue, myCustomValue)
}
}
MyView()
.myCustomValue("Another string")
struct MyView: View {
@Environment(\.myCustomValue) var customValue: String
var body: some View {
Text(customValue) // Displays "Another value".
}
}
Availability¶
iOS 13.0+
macOS 10.15+
tvOS 13.0+
watchOS 6.0+
Topics¶
Type Property¶
defaultValue The default value for the environment key.
Associated Type¶
Value The associated type representing the type of the environment key's value.