如何创建可以在 Key 中保存任何内容的 Dictionary?或者它能够容纳的所有可能的类型 [英] How to create Dictionary that can hold anything in Key? or all the possible type it capable to hold
问题描述
我想创建一个不限制键类型的Dictionary
(比如NSDictionary
)
I want to create a Dictionary
that does not limit the key type (like NSDictionary
)
所以我尝试了
var dict = Dictionary<Any, Int>()
和
var dict = Dictionary<AnyObject, Int>()
结果
error: type 'Any' does not conform to protocol 'Hashable'
var dict = Dictionary<Any, Int>()
^
<REPL>:5:12: error: cannot convert the expression's type '<<error type>>' to type '$T1'
var dict = Dictionary<Any, Int>()
^~~~~~~~~~~~~~~~~~~~~~
好的,我会使用Hashable
var dict = Dictionary<Hashable, Int>()
但是
error: type 'Hashable' does not conform to protocol 'Equatable'
var dict = Dictionary<Hashable, Int>()
^
Swift.Equatable:2:8: note: '==' requirement refers to 'Self' type
func ==(lhs: Self, rhs: Self) -> Bool
^
Swift.Hashable:1:10: note: type 'Hashable' does not conform to inherited protocol 'Equatable.Protocol'
protocol Hashable : Equatable
^
<REPL>:5:12: error: cannot convert the expression's type '<<error type>>' to type '$T1'
var dict = Dictionary<Hashable, Int>()
^~~~~~~~~~~~~~~~~~~~~~~~~~~
所以Hashable
继承自Equatable
但不符合Equatable
???没看懂...
So Hashable
inherited from Equatable
but it does not conform to Equatable
??? I don't understand...
无论如何,继续努力
typealias KeyType = protocol<Hashable, Equatable> // KeyType is both Hashable and Equatable
var dict = Dictionary<KeyType, Int>() // now you happy?
没有运气
error: type 'KeyType' does not conform to protocol 'Equatable'
var dict = Dictionary<KeyType, Int>()
^
Swift.Equatable:2:8: note: '==' requirement refers to 'Self' type
func ==(lhs: Self, rhs: Self) -> Bool
^
Swift.Hashable:1:10: note: type 'KeyType' does not conform to inherited protocol 'Equatable.Protocol'
protocol Hashable : Equatable
^
<REPL>:6:12: error: cannot convert the expression's type '<<error type>>' to type '$T1'
var dict = Dictionary<KeyType, Int>()
^~~~~~~~~~~~~~~~~~~~~~~~~~
我现在很迷茫,我怎样才能让编译器对我的代码满意?
I am so lost now, how can I make compiler happy with my code?
我想像这样使用字典
var dict = Dictionary<Any, Int>()
dict[1] = 2
dict["key"] = 3
dict[SomeEnum.SomeValue] = 4
<小时>
我知道我可以使用 Dictionary
,但这并不是我真正想要的.
I know I can use Dictionary<NSObject, Int>
, but it is not really what I want.
推荐答案
Swift 3 更新
您现在可以使用 AnyHashable
,它是一个类型擦除的可哈希值,专为这样的场景创建:
Swift 3 update
You can now use AnyHashable
which is a type-erased hashable value, created exactly for scenarios like this:
var dict = Dictionary
这篇关于如何创建可以在 Key 中保存任何内容的 Dictionary?或者它能够容纳的所有可能的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!