Converting Boolean value to Integer value in Swift
boolean, integer, swift, swift3
Solution
Swift 5
Bool -> Int
extension Bool {
var intValue: Int {
return self ? 1 : 0
}
}
Int -> Bool
extension Int {
var boolValue: Bool {
return self != 0
}
}
Problem
I was converting from Swift 2 to Swift 3. I noticed that I cannot convert a boolean value to integer value in Swift 3. ``` let p1 = ("a" == "a") //true print(true) //"true\n" print(p1) //"true\n" Int(true) //1 Int(p1) //error ``` For example these syntaxes worked fine in Swift 2. But in Swift 3, `print(p1)` yields an error. The error is `error: cannot invoke initializer for type 'Int' with an argument list of type '((Bool))'` I understand why the errors are happening. Can anyone explain what is the reason for this safety and how to convert from Bool to Int in Swift 3?