【问题标题】:Understanding EnvironmentValues syntax了解 EnvironmentValues 语法
【发布时间】:2021-12-12 00:20:28
【问题描述】:

我花了一些时间试图理解EnvironmentValues 中使用的语法,我希望有人能指出我是否犯了任何错误。

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

我的理解是 getter 和 setter 的主体使用 下标语法,其中第一个 selfEnvironmentValues 字典作为对象引用。方括号允许将键传递给该对象。密钥本身是SensitiveKey元类型实例,它是先前定义的EnvironmentKey。它允许访问任何类型的属性和方法,在这种情况下,这将是EnvironmentKey 所需的defaultValue

我是否理解正确?如果您能澄清我在这里的任何误解,我将不胜感激。

干杯。

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    你很接近。 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)
        }
    }
    

    密钥只是一个 EnvironmentKey,而不是 isSensitive 的元类型。它实际上是 EnvironmentValues 中字典值的关键。 defaultValue 是一个糟糕的名称选择,它暗示了可变性,因为密钥本身是不可变的。

    另外,当您看到.self 时,它就是该类型的当前实例。 .Self 将引用类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多