依赖于 hashValue 来判断枚举情况是否合理吗?

18 浏览
0 Comments

依赖于 hashValue 来判断枚举情况是否合理吗?

在审查一些代码时,我发现一个实现为Rank枚举的代码块:

enum Rank: String {

case first

case second

case third

}

然而,令我惊讶的是,我看到类似于这样的代码:

let gold = [300, 200, 100]

let firstPrize = gold[Rank.first.hashValue] // 300

这意味着Rank.first.hashValue被用作索引!乍一看,使用哈希值作为数组索引似乎不是一个好主意:

哈希值在程序的不同执行之间不能保证相等。不要保存哈希值以在将来的执行中使用。

hashValue

然而,这从未引起过问题(至少他们是这样说的)。

我尝试通过实现以下内容来追踪问题:

print(Rank.first.hashValue) // 0

print(Rank.second.hashValue) // 1

print(Rank.third.hashValue) // 2

我看到的输出始终是相同的。

虽然我们可以在枚举中声明一个属性来实现这样的功能,例如:

var index: Int {

switch self {

case .first:

return 0

case .second:

return 1

case .third:

return 2

}

}

因此:

let firstPrize = gold[Rank.first.index] // 300

但我更想知道为什么在这种情况下使用hashValue似乎是可以的?这可能与我对hashValue的确切理解有关吗?

0