【问题标题】:How can I extend dictionaries whose values are dictionaries themselves?如何扩展其值本身就是字典的字典?
【发布时间】:2017-01-10 13:14:38
【问题描述】:

假设我想用一些功能扩展嵌套字典。使用伪 Swift,这是我的目标:

extension Dictionary where Value: Dictionary {
    typealias K1 = Key
    typealias K2 = Value.Key
    typealias V  = Value.Value

    subscript(k1: K1, k2: K2) -> V? {
        return self[k1]?[k2]
    }
}

不过,我无法让它工作。类型边界不能是非协议类型; Dictionary 实现的协议没有提供我需要引用的方法和类型;访问泛型类型很麻烦;等等。我试过的都没有成功。

对此有什么解决方案?

【问题讨论】:

    标签: swift dictionary generics swift-extensions


    【解决方案1】:

    我们可以在这里使用的一个技巧(我敢说模式吗?)是定义我们的自己的协议(我们从不打算在其他任何地方使用它)声明我们需要的所有东西,我们知道Dictionary无论如何都符合。

    protocol DictionaryProtocol {
        associatedtype Key: Hashable
        associatedtype Value
    
        subscript(key: Key) -> Value? { get set }
    }
    
    extension Dictionary: DictionaryProtocol {}
    
    extension Dictionary where Value: DictionaryProtocol {
        typealias K1 = Key
        typealias K2 = Value.Key
        typealias V  = Value.Value
    
        subscript(k1: K1, k2: K2) -> V? {
            return self[k1]?[k2]
        }
    }
    

    此解决方案适用于数组数组,可能还有许多类似的情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多