相关疑难解决方法(0)

将Int转换为Bool

在Swift 2.x中我相信我能做到:

let number = 1
let result = Bool(number)

print(result) // prints out: true
Run Code Online (Sandbox Code Playgroud)

但是自从Swift 3以来我一直无法做到这一点并且它给了我错误:

无法使用类型'(Int)'的参数列表调用类型'Bool'的初始化程序

目前我正在使用扩展转换Int为a,Bool但我想知道是否没有构建选项来执行此操作.

int boolean swift swift3

28
推荐指数
5
解决办法
3万
查看次数

Swift4转换后,"'init'已被弃用"警告

在Swift3中,我之前使用以下方法将Bool转换为Int

let _ = Int(NSNumber(value: false))
Run Code Online (Sandbox Code Playgroud)

转换为Swift4后,我得到了一个"'init'被弃用"警告.怎么办呢?

swift swift4

15
推荐指数
2
解决办法
5652
查看次数

为什么Int(false)有效,但Int(booleanVariable)不起作用?

代码如下所示:

Int(false) // = 1, it's okay

//but when I try this
let emptyString = true //or let emptyString : Bool = true
Int(emptyString) //error - Cannot invoke initializer with an argument list of type '(Bool)'
Run Code Online (Sandbox Code Playgroud)

谁能解释这个事实?令人困惑。内部会发生什么?

swift swift3

3
推荐指数
1
解决办法
347
查看次数

Bool.hashValue有效转换为Int吗?

在某些情况下,我看到的一些代码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没有可靠的转换方法?

hash boolean type-conversion swift swift4

2
推荐指数
1
解决办法
661
查看次数

标签 统计

swift ×4

boolean ×2

swift3 ×2

swift4 ×2

hash ×1

int ×1

type-conversion ×1