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?
To convert boolean to integer, let us first declare a variable of boolean primitive. boolean bool = true; Now, to convert it to integer, let us now take an integer variable and return a value “1” for “true” and “0” for “false”. int val = (bool) ?
Nope, bools are designed to only store a 1 or a 0.
Boolean values and operations Constant true is 1 and constant false is 0.
Bool represents Boolean values in Swift. Create instances of Bool by using one of the Boolean literals true or false , or by assigning the result of a Boolean method or operation to a variable or constant.
You could use the ternary operator to convert a Bool to Int:
let result = condition ? 1 : 0
result
will be 1 if condition
is true, 0 is condition
is false.
Bool -> Int
extension Bool { var intValue: Int { return self ? 1 : 0 } }
Int -> Bool
extension Int { var boolValue: Bool { return self != 0 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With