如何扩展词典本身的词典? [英] How can I extend dictionaries whose values are dictionaries themselves?

查看:141
本文介绍了如何扩展词典本身的词典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

pre $扩展字典其中值字典{
typealias K1 = Key
typealias K2 = Value.Key
typealias V = Value.Value

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



不过,我无法得到这个工作。类型边界不能是非协议类型; Dictionary实现的协议没有提供我需要引用的方法和类型;获得这种类型的泛型非常麻烦;等等。没什么我试过的。



这是什么解决方案?

解决方案

我们可以在这里使用的一个技巧(我敢说模式?)是定义我们自己的协议(我们从来不打算在其他任何地方使用它),它声明了我们需要的所有东西,我们知道<$ c

$ p $协议DictionaryProtocol {
associatedtype Key:$ c $>字典符合,无论如何。

可散列的
associatedtype值

下标(键:键) - >值? {get set}
}

扩展词典:DictionaryProtocol {}

扩展词典其中Value:DictionaryProtocol {
typealias K1 =键
typealias K2 = Value.Key
typealias V = Value.Value

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

这个解决方案继承了数组的数组,可能还有许多类似的情况。


Say I want to extend nested dictionaries with some functionality. Using pseudo-Swift, this is my goal:

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]
    }
}

I can not get this to work, though. Type bounds can not be non-protocol types; no protocol that Dictionary implements provides the methods I and types I need to refer to; getting access to the types of generics is cumbersome; and so on. Nothing I tried works out.

What is a solution for this?

解决方案

One trick (dare I say pattern?) we can use here is to define our own protocol (which we never intend to use anywhere else) which declares all we need and we know Dictionary conforms to, anyway.

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]
    }
}

This solution carries over to arrays of arrays, and probably many similar cases.

这篇关于如何扩展词典本身的词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆