Converting Boolean value to Integer value in swift

2019-01-23 23:18发布

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?

标签: swift3
6条回答
叼着烟拽天下
2楼-- · 2019-01-24 00:00

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)).")
查看更多
对你真心纯属浪费
3楼-- · 2019-01-24 00:02

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))   
查看更多
仙女界的扛把子
4楼-- · 2019-01-24 00:07

Swift 4

Bool -> Int

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

Int -> Bool

extension Int {
    var boolValue: Bool {
        return self != 0 
    }
}
查看更多
该账号已被封号
5楼-- · 2019-01-24 00:12

Try this,

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

Int(true)             //1

Int(NSNumber(value:p1)) //1
查看更多
劫难
6楼-- · 2019-01-24 00:16

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.

查看更多
聊天终结者
7楼-- · 2019-01-24 00:21

You could use hashValue property:

let active = true
active.hashValue // returns 1
active = false
active.hashValue // returns 0
查看更多
登录 后发表回答