Shubhashis
Shubhashis

Reputation: 10631

Converting Boolean value to Integer value in Swift

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?

Upvotes: 45

Views: 57846

Answers (10)

Tyson Freeze
Tyson Freeze

Reputation: 133

This is my preferred adaptation of existing solutions, just an overload of Int. This way I don't have to remember any additional syntax.

func Int(_ boolean: Bool) -> Int {
    boolean ? 1 : 0
}

Upvotes: 0

Xiaomu Gu
Xiaomu Gu

Reputation: 31

In swift 5:

you can do this:

let x = ("a" == "a")

Int(truncating: x as NSNumber)

Upvotes: 0

user17800642
user17800642

Reputation: 21

unsafeBitCast is always an option

let int: Int = Int(unsafeBitCast(someBool, to: UInt8.self))

Upvotes: 2

ObjectiveCesar
ObjectiveCesar

Reputation: 61

Swift 5.4

This is a more generic approach which is applicable for other types than just 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

Upvotes: 6

Nike Kov
Nike Kov

Reputation: 13760

Swift 5

Bool -> Int

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

Int -> Bool

extension Int {
    var boolValue: Bool {
        return self != 0 
    }
}

Upvotes: 67

user1101733
user1101733

Reputation: 258

Tested in swift 3.2 and swift 4

There is not need to convert it into Int

Try this -

let p1 = ("a" == "a") //true

print(true)           //"true\n"
print(p1)             //"true\n"

Int(true)             //1

print(NSNumber(value: p1))   

Upvotes: 0

Balaji Malliswamy
Balaji Malliswamy

Reputation: 649

Try this,

let p1 = ("a" == "a") //true
print(true)           //"true\n"
print(p1)             //"true\n"

Int(true)             //1

Int(NSNumber(value:p1)) //1

Upvotes: 21

Arturo Rivas Arias
Arturo Rivas Arias

Reputation: 73

You could use hashValue property:

let active = true
active.hashValue // returns 1
active = false
active.hashValue // returns 0

Upvotes: 0

diatrevolo
diatrevolo

Reputation: 2822

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.

extension Bool: IntValue {
    func intValue() -> Int {
        if self {
            return 1
        }
        return 0
    }
}

protocol IntValue {
    func intValue() -> Int
}

print("\(true.intValue())") //prints "1"

EDIT- To cover an example of the case mentioned by Rob Napier in the comments below, one could do something like this:

extension Int {
    init(_ bool:Bool) {
        self = bool ? 1 : 0
    }
}

let myBool = true
print("Integer value of \(myBool) is \(Int(myBool)).")

Upvotes: 13

Eric Aya
Eric Aya

Reputation: 70119

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.

Upvotes: 74

Related Questions