加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:07:18 所属栏目:百科 来源:网络整理
导读:我想创建一个不限制键类型的字典(如NSDictionary) 所以我试过 var dict = DictionaryAny,Int() 和 var dict = DictionaryAnyObject,Int() 结果 error: type 'Any' does not conform to protocol 'Hashable'var dict = DictionaryAny,Int() ^REPL:5:12: error
我想创建一个不限制键类型的字典(如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,以及在==运算符内。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读