0

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?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • Better not. It brakes in Swift 4.2, see https://stackoverflow.com/q/51205254/1187415 (duplicate?) – Martin R Jul 10 '18 at 13:55
  • It's not ok. It may have worked in that case but there is no guarantee it will continue to do so and as @MartinR has said it will break in Swift 4.2. – Upholder Of Truth Jul 10 '18 at 14:34
  • In Swift 4.2 you can define `var index: Int { return Rank.allCases.index(of: self)! }` as a computed property. – Martin R Jul 10 '18 at 14:36
  • It might be instructive to read https://github.com/apple/swift-evolution/blob/master/proposals/0194-derived-collection-of-enum-cases.md, where similar pre-Swift-4.2 techniques are presented: *"They are dangerous at worst, bug-prone in most cases ..., and awkward at best."* – Martin R Jul 10 '18 at 14:41

0 Answers0