Bool.hashValue valid to convert to Int?

Viewed 1601

In some cases and some code I saw that hashValue is used to convert Bool to Int.

However, the code

let someValue = true
let someOtherValue = false

print(someValue.hashValue)
print(someOtherValue.hashValue)

gets me the output

-5519895559129191040
7814522403520016984

I would expect 1 and 0, though.

I use XCode 10.0 beta 2 (10L177m), MacOS High Sierra with Swift 4.2. I can switch to Swift 4.0 to gain likewise results.

Now, is there something I do wrong or is hashValue no reliable conversion method?

2 Answers

No, hashValue is not a proper way to convert some other type to an Int, especially if you want specific results.

From the documentation for Hashable hashValue:

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.

The simplest solution to convert a Bool to Int is:

let someInt = someBool ? 1 : 0

is hashValue no reliable conversion method?

From the .hashValue Documentation:

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.

Related