【发布时间】:2015-01-05 10:01:39
【问题描述】:
我在 Swift 中的字典中有一个很大的问题。我有一些自定义类:Team、Competition 和 Statistics。 Team 和 Competition 符合 Hashable 和 Equatable 协议。
字典如下所示:
[Team: [Competition: Statistics]]。
此外,我有两个“总体价值观”:团队和竞争。
当我执行以下操作时:
println(dictionary[overallTeam]!)
它会打印比赛的内存地址和您所期望的统计数据。但是,当我执行以下操作时:
println(dictionary[overallTeam]![overallCompetition])
我得到nil 作为输出。我完全想知道这一点,因为dictionary[overallTeam]! 中只有一个与overallCompetition 同名的键。这意味着等号符号 == 返回 true 并且 hashValue 是相同的。
请帮忙,这会是哪里的问题。
代码如下:
在init() 方法中,我执行以下操作:
dictionary = [Team: [Competition: Statistics]]()
dictionary[overallTeam] = [Competition: Statistics]()
dictionary[overallTeam]![overallCompetition] = Statistics()
打印代码在启动应用程序时调用的方法中:
println(overallCompetition.name) //"overallCompetition"
println(overallCompetition.hashValue) //some hashCode, e.g. 5
for item in dictionary[overallTeam]!.keys { //executed once
println(item.name) //"overallCompetition"
println(item.hashValue) //SAME hashCode, e.g. 5
println(dictionary[overallTeam]![item]!.value) //prints the value expected
}
println(dictionary[overallTeam]) //prints some memory addresses
println(dictionary[overallTeam]![overallCompetition]) //nil
println(dictionary[overallTeam]![overallCompetition]!.value) //error: unexpectedly found nil
只是一个一般性问题:字典键基于 hashValue,不是吗?那么为什么使用 same hashValue 的两个键不会产生 same 结果???
【问题讨论】:
-
能否请您发布设置和打印字典变量的代码。
-
您的字典将内部字典定义为具有 Statistics 键,但内部字典使用 PlayerStatistics 键初始化,然后将值初始化为 Statistics 对象... Statistics 是 PlayerStatistics 的子类还是PlayerStatistics 是 Statistics 的子类,因为您的代码有点暗示两者都是彼此的子类。将内部字典的值类型更改为 Statistics 并查看是否有效。
-
哦,抱歉,忘记改了,改了名字,这样就不会那么长了。
-
你找到解决办法了吗?
标签: swift dictionary