Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Boolean value to Integer value in swift 3

Tags:

swift3

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?

like image 408
Shubhashis Avatar asked Oct 25 '16 14:10

Shubhashis


People also ask

How do you convert a boolean to an integer?

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) ?

Can boolean be stored in int?

Nope, bools are designed to only store a 1 or a 0.

What is the integer value for boolean true?

Boolean values and operations Constant true is 1 and constant false is 0.

What is the difference between bool and boolean in Swift?

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.


2 Answers

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.

like image 166
Eric Aya Avatar answered Oct 17 '22 01:10

Eric Aya


Swift 5

Bool -> Int

extension Bool {     var intValue: Int {         return self ? 1 : 0     } } 

Int -> Bool

extension Int {     var boolValue: Bool {         return self != 0      } } 
like image 24
Nik Kov Avatar answered Oct 17 '22 00:10

Nik Kov