在swift 3中将布尔值转换为Integer值

Shu*_*his 27 swift3

我正在从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为假.

  • 好的,所以从布尔值到整数值的转换是不是在swift 3中? (3认同)
  • 我不相信这种转换真的是Swift的一部分.我相信这是通过NSNumber进行隐式转换的副作用.隐式Bool/Int转换是C中错误的旧来源(特​​别是因为像"2"这样的非零数字是"true-ish"但不等于"true").斯威夫特积极尝试避免这些历史性的漏洞来源. (2认同)

小智 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)

  • 似乎已弃用 (2认同)

Nik*_*Kov 19

斯威夫特4

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)

  • 打败我!这绝对是我首选的解决方案。它比这里的其他解决方案更符合 Swift 约定。 (2认同)

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

斯威夫特 5.4

这是一种更通用的方法,不仅适用于 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)