Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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,
@H_874_6@
@H_874_6@
我想创建一个不限制键类型的字典(如NSDictionary) @H_874_15@所以我试

var Dict = Dictionary<Any,Int>()
@H_874_15@和

var Dict = Dictionary<AnyObject,Int>()
@H_874_15@结果

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>()
           ^~~~~~~~~~~~~~~~~~~~~~
@H_874_15@OK,我将使用Hashable

var Dict = Dictionary<Hashable,Int>()
@H_874_15@但

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>()
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~
@H_874_15@所以Hashable继承自Equatable,但它不符合Equatable ???我不明白…

@H_874_15@反正,不断尝试

typealias KeyType = protocol<Hashable,Equatable> // KeyType is both Hashable and Equatable
var Dict = Dictionary<KeyType,Int>() // Now you happy?
@H_874_15@没有运气

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>()
           ^~~~~~~~~~~~~~~~~~~~~~~~~~
@H_874_15@我现在这么迷路,我怎么能让编译器满意我的代码

@H_874_15@我想使用字典

var Dict = Dictionary<Any,Int>()
Dict[1] = 2
Dict["key"] = 3
Dict[SomeEnum@L_838_4@meValue] = 4
@H_874_15@我知道我可以使用Dictionary< NSObject,Int&gt,但它不是我真正想要的。

我相信,从Swift 1.2,你可以使用ObjectIdentifier结构体。它实现了Hashable(因此EquatablE)以及Comparable。您可以使用它来包装任何类实例。我猜测的实现使用包装对象的底层地址为hashValue,以及在==运算符内。

大佬总结

以上是大佬教程为你收集整理的swift – 如何创建可以在Key中保存任何内容的字典?或者它能够保持的所有可能的类型全部内容,希望文章能够帮你解决swift – 如何创建可以在Key中保存任何内容的字典?或者它能够保持的所有可能的类型所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
猜你在找的Swift相关文章