Instance Subscript

subscript(_:)

Accesses the environment value associated with a custom key. あつらえのキーと結び付けられた環境値にアクセスします。

Declaration 宣言

subscript<K>(key: K.Type) -> K.Value where K : EnvironmentKey { get set }

Overview 概要

Create custom environment values by defining a key that conforms to the EnvironmentKey protocol, and then using that key with the subscript operator of the EnvironmentValues structure to get and set a value for that key:


private struct MyEnvironmentKey: EnvironmentKey {
    static let defaultValue: String = "Default value"
}


extension EnvironmentValues {
    var myCustomValue: String {
        get { self[MyEnvironmentKey.self] }
        set { self[MyEnvironmentKey.self] = newValue }
    }
}

You use custom environment values the same way you use system-provided values, setting a value with the environment(_:_:) view modifier, and reading values with the Environment property wrapper. You can also provide a dedicated view modifier as a convenience for setting the value:


extension View {
    func myCustomValue(_ myCustomValue: String) -> some View {
        environment(\.myCustomValue, myCustomValue)
    }
}

See Also 参照

Creating and Accessing Values