gpt4 book ai didi

swift - Bool.hashValue 转换为 Int 有效吗?

转载 作者:可可西里 更新时间:2023-10-31 23:59:40 25 4
gpt4 key购买 nike

在某些情况下和一些代码中,我看到 hashValue 用于将 Bool 转换为 Int

但是,代码

let someValue = true
let someOtherValue = false

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

获取输出

-5519895559129191040
7814522403520016984

不过,我希望有 10

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

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

最佳答案

不,hashValue 不是将某些其他类型转换为 Int 的正确方法,尤其是当您需要特定结果时。

来自 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.

Bool 转换为 Int 的最简单解决方案是:

let someInt = someBool ? 1 : 0

关于swift - Bool.hashValue 转换为 Int 有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52116428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com