static var defaultValue : Self.Value
associatedtype Value
Availability 有効性
Technology
protocol EnvironmentKey
You can create custom environment values by extending the Environment
structure with new properties. First declare a new environment key type and specify a value for the required default
property:
private struct MyEnvironmentKey: EnvironmentKey {
static let defaultValue: String = "Default value"
}
The Swift compiler automatically infers the associated Value
type as the type you specify for the default value. Then use the key to define a new environment value property:
extension EnvironmentValues {
var myCustomValue: String {
get { self[MyEnvironmentKey.self] }
set { self[MyEnvironmentKey.self] = newValue }
}
}
Clients of your environment value never use the key directly. Instead, they use the key path of your custom environment value property. To set the environment value for a view and all its subviews, add the environment(_:
view modifier to that view:
MyView()
.environment(\.myCustomValue, "Another string")
As a convenience, you can also define a dedicated view modifier to apply this environment value:
extension View {
func myCustomValue(_ myCustomValue: String) -> some View {
environment(\.myCustomValue, myCustomValue)
}
}
This improves clarity at the call site:
MyView()
.myCustomValue("Another string")
To read the value from inside My
or one of its descendants, use the Environment
property wrapper:
struct MyView: View {
var customValue: String (\.myCustomValue)
var body: some View {
Text(customValue) // Displays "Another string".
}
}
static var defaultValue : Self.Value
associatedtype Value
struct Environment
struct EnvironmentValues