pakobongbong
pakobongbong

Reputation: 173

Understanding EnvironmentValues syntax

I was spending some time trying to understand the syntax used in EnvironmentValues and I was hoping someone could point out if I have made any errors.

extension EnvironmentValues {
    var isSensitive: Bool {
        get { self[SensitiveKey.self] }
        set { self[SensitiveKey.self] = newValue }
    }
}

My understanding is that the the body of the getter and setter is using subscript syntax where the first self is referring to the EnvironmentValues dictionary as an object. The square brackets allows for a key to be passed into this object. The key itself is a metatype instance of SensitiveKey which is a previously defined EnvironmentKey. It allows access to any type properties and methods, which in this case would be the required defaultValue for the EnvironmentKey.

Have I understood this correctly? I'd really appreciate if you could clarify any misunderstandings I have here.

Cheers.

Upvotes: 0

Views: 150

Answers (1)

Yrb
Yrb

Reputation: 9695

You are close. Per the Swift Documentation:

private struct SensitiveKey: EnvironmentKey {
    static let defaultValue: String = "SensitiveKey" // the default could be anything unique

}

extension EnvironmentValues {
    var isSensitive: String {
        get { self[SensitiveKey.self] }
        set { self[SensitiveKey.self] = newValue }
    }
}

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

The key is just an EnvironmentKey, not a meta type for isSensitive. It is literally the key to the dictionary value in EnvironmentValues. defaultValue is a poor choice of name that implies mutability as the key itself is immutable.

Also, when you see .self, it is the current instance of the type. .Self would refer to the type.

Upvotes: 2

Related Questions