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?
EDIT - From conversations in the comments, it is becoming clearer that the second way of doing this below (Int.init overload) is more in the style of where Swift is headed.
Alternatively, if this were something you were doing a lot of in your app, you could create a protocol and extend each type you need to convert to
Int
with it.EDIT- To cover an example of the case mentioned by Rob Napier in the comments below, one could do something like this:
Tested in swift 3.2 and swift 4
There is not need to convert it into Int
Try this -
Swift 4
Try this,
You could use the ternary operator to convert a Bool to Int:
result
will be 1 ifcondition
is true, 0 iscondition
is false.You could use hashValue property: