Bool.hashValue valid to convert to Int?

对着背影说爱祢 提交于 2020-12-11 18:42:29

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/52116428/bool-hashvalue-valid-to-convert-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!