Bool.hashValue有效转换为Int吗?

Ice*_*ire 2 hash boolean type-conversion swift swift4

在某些情况下,我看到的一些代码hashValue用于转换BoolInt.

但是,代码

let someValue = true
let someOtherValue = false

print(someValue.hashValue)
print(someOtherValue.hashValue)
Run Code Online (Sandbox Code Playgroud)

得到我的输出

-5519895559129191040
7814522403520016984
Run Code Online (Sandbox Code Playgroud)

我希望10,虽然.

我使用XCode 10.0 beta 2(10L177m),MacOS High Sierra和Swift 4.2.我可以切换到Swift 4.0以获得同样的结果.

现在,有什么我做错了或hashValue没有可靠的转换方法?

rma*_*ddy 5

不,hashValue不是将其他类型转换为a的正确方法Int,特别是如果您想要特定结果.

从以下文档Hashable hashValue:

在程序的不同执行中,哈希值不保证相等.不要保存在将来执行期间使用的哈希值.

转换一个最简单的解决方案Bool,以Int是:

let someInt = someBool ? 1 : 0
Run Code Online (Sandbox Code Playgroud)