swift – 如何创建可以在Key中保存任何内容的字典?或者它能够保持的所有可能的类型

前端之家收集整理的这篇文章主要介绍了swift – 如何创建可以在Key中保存任何内容的字典?或者它能够保持的所有可能的类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想创建一个不限制键类型的字典(如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>()
           ^~~~~~~~~~~~~~~~~~~~~~

OK,我将使用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 ???我不明白…

反正,不断尝试

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,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>()
           ^~~~~~~~~~~~~~~~~~~~~~~~~~

我现在这么迷路,我怎么能让编译器满意我的代码

我想使用字典

var dict = Dictionary<Any,Int>()
dict[1] = 2
dict["key"] = 3
dict[SomeEnum.SomeValue] = 4

我知道我可以使用Dictionary< NSObject,Int&gt,但它不是我真正想要的。

我相信,从Swift 1.2,你可以使用ObjectIdentifier结构体。它实现了Hashable(因此Equatable)以及Comparable。您可以使用它来包装任何类实例。我猜测的实现使用包装对象的底层地址为hashValue,以及在==运算符内。
原文链接:https://www.f2er.com/swift/321200.html

猜你在找的Swift相关文章