Ice*_*ire 2 hash boolean type-conversion swift swift4
在某些情况下,我看到的一些代码hashValue
用于转换Bool
为Int
.
但是,代码
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)
我希望1
和0
,虽然.
我使用XCode 10.0 beta 2(10L177m),MacOS High Sierra和Swift 4.2.我可以切换到Swift 4.0以获得同样的结果.
现在,有什么我做错了或hashValue
没有可靠的转换方法?
不,hashValue
不是将其他类型转换为a的正确方法Int
,特别是如果您想要特定结果.
从以下文档Hashable hashValue
:
在程序的不同执行中,哈希值不保证相等.不要保存在将来执行期间使用的哈希值.
转换一个最简单的解决方案Bool
,以Int
是:
let someInt = someBool ? 1 : 0
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
661 次 |
最近记录: |