【问题标题】:Swift dictionary not working斯威夫特字典不起作用
【发布时间】:2015-01-05 10:01:39
【问题描述】:

我在 Swift 中的字典中有一个很大的问题。我有一些自定义类:TeamCompetitionStatisticsTeamCompetition 符合 HashableEquatable 协议。

字典如下所示: [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


【解决方案1】:

您无法将字符串与不同的对象类型进行比较并获得一致的结果,因为这种关系不是自反的。换句话说,虽然您可能已经实现了 Equatable 来表示您的对象 == 字符串,但事实并非如此,因此字符串 == 对象会破坏它。

由于您是按字符串名称对数组进行索引,因此您永远无法使用overallCompetition 找到它。将第二个字典存储为 overallCompetition 作为值,或者使用整体竞争名称来提取值。

【讨论】:

  • 我不是在比较一个字符串和一个对象——只比较两个对象的两个字符串
  • 您的代码表明“overallCompetition”是一种对象类型,而您发布的代码表明您的字典按字符串存储键。因此,您的代码要么需要在其查找中包含overallCompetition.name,要么需要将对象存储为键。
  • 键是外部字典中的Team对象和内部字典中的竞争对象
  • 我的错,对不起。如果你先提取出内联表达式dictionary[overallTeam]!,它是否有效?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 2019-08-02
  • 2017-07-22
  • 2017-03-24
  • 2016-02-16
  • 2016-12-27
  • 1970-01-01
相关资源
最近更新 更多