是否可以将Bool.hashValue转换为Int? [英] Bool.hashValue valid to convert to Int?

查看:74
本文介绍了是否可以将Bool.hashValue转换为Int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是,代码

let someValue = true
let someOtherValue = false

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

让我得到输出

-5519895559129191040
7814522403520016984

不过,我希望 1 0 .

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

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.

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

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

推荐答案

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

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

来自 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 的最简单解决方案是:

The simplest solution to convert a Bool to Int is:

let someInt = someBool ? 1 : 0

这篇关于是否可以将Bool.hashValue转换为Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆