我在Swift中的字典中遇到了一个很大的问题。我有一些自定义类:团队,竞争和统计。 团队和比赛符合协议哈希和可衡量的。Swift dictionary does not working
字典看起来像这样: [Team: [Competition: Statistics]]
。
此外我有两个“总体价值”:团队和竞争。
当我做到以下几点: println(dictionary[overallTeam]!)
它打印出的竞争和统计数据,你会期望的内存地址。但是,当我执行以下操作时: println(dictionary[overallTeam]![overallCompetition])
我得到nil
作为输出。我完全想知道,因为dictionary[overallTeam]!
中只有1个密钥,它与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的,不是吗?然后为什么做两个键与相同 hashValue不会产生相同结果???
请问您可以发布设置和打印字典变量的代码。 –
您的词典将内部词典定义为具有统计密钥,但内部词典使用PlayerStatistics键进行初始化,然后将该值初始化为统计对象...是统计PlayerStatistics的子类或是PlayerStatistics统计的子类,因为你的代码暗示着两者都是彼此的子类。将内部字典的值类型更改为统计信息并查看是否有效。 – ad121
哦,对不起,忘了改变它,改变了名字,以便它们在这里不那么久。 – borchero