Is it sensible to rely on hashValue for enum cases

2019-09-01 04:10发布

问题:

While reviewing some code, I found a Rank enum implemented as:

enum Rank: String {
    case first
    case second
    case third
}

However, the surprising part for me was that I saw a code similar to this:

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

means that Rank.first.hashValue has been used as an index! For the first look, it seems to be not a good idea to use a hash value as an index for an array:

Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution.

hashValue

Nevertheless it never causes an issue (at least that's what they said).

I tried to trace the issue, by implementing:

print(Rank.first.hashValue) // 0
print(Rank.second.hashValue) // 1
print(Rank.third.hashValue) // 2

and I saw is the output is always the same.

Although we could declare a property in the enum to do such a functionality, as:

var index: Int {
    switch self {
    case .first:
        return 0
    case .second:
        return 1
    case .third:
        return 2
    }
}

hence:

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

I would prefer to know why using the hashValue seems to be ok in this case? Could it be related to: I misunderstand what exactly is hashValue?

标签: swift hash enums