我正在从swift 2转换为swift 3.我注意到我无法在swift 3中将布尔值转换为整数值:\.
let p1 = ("a" == "a") //true
print(true) //"true\n"
print(p1) //"true\n"
Int(true) //1
Int(p1) //error
Run Code Online (Sandbox Code Playgroud)
例如,这些语法在swift 2中运行良好.但在swift 3中,会print(p1)产生错误.
错误是 error: cannot invoke initializer for type 'Int' with an argument list of type '((Bool))'
我明白为什么错误发生了.任何人都可以解释这种安全性的原因以及如何在swift 3中将Bool转换为Int?
aya*_*aio 46
您可以使用三元运算符将Bool转换为Int:
let result = condition ? 1 : 0
Run Code Online (Sandbox Code Playgroud)
result如果condition为真,则为1,0 condition为假.
小智 22
试试这个,
let p1 = ("a" == "a") //true
print(true) //"true\n"
print(p1) //"true\n"
Int(true) //1
Int(NSNumber(value:p1)) //1
Run Code Online (Sandbox Code Playgroud)
Nik*_*Kov 19
Bool - > Int
extension Bool {
var intValue: Int {
return self ? 1 : 0
}
}
Run Code Online (Sandbox Code Playgroud)
Int - >布尔
extension Int {
var boolValue: Bool {
return self != 0
}
}
Run Code Online (Sandbox Code Playgroud)
dia*_*olo 12
编辑 - 从评论中的对话中,越来越清楚的是,下面这样做的第二种方式(Int.init重载)更符合Swift前进的风格.
或者,如果您在应用程序中执行了大量操作,则可以创建协议并扩展您需要转换为Int它的每种类型.
extension Bool: IntValue {
func intValue() -> Int {
if self {
return 1
}
return 0
}
}
protocol IntValue {
func intValue() -> Int
}
print("\(true.intValue())") //prints "1"
Run Code Online (Sandbox Code Playgroud)
编辑 - 为了覆盖Rob Napier在下面的评论中提到的案例,人们可以这样做:
extension Int {
init(_ bool:Bool) {
self = bool ? 1 : 0
}
}
let myBool = true
print("Integer value of \(myBool) is \(Int(myBool)).")
Run Code Online (Sandbox Code Playgroud)
小智 5
这是一种更通用的方法,不仅适用于 Int,还适用于其他类型。
extension ExpressibleByIntegerLiteral {
init(_ booleanLiteral: BooleanLiteralType) {
self = booleanLiteral ? 1 : 0
}
}
let bool1 = true
let bool2 = false
let myInt = Int(bool1) // 1
let myFloat = Float(bool1) // 1
let myDouble = Double(bool2) // 0
let myCGFloat = CGFloat(bool2) // 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29807 次 |
| 最近记录: |