Converting Boolean value to Integer value in swift 3

前端 未结 7 903
予麋鹿
予麋鹿 2020-12-15 15:56

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
         


        
相关标签:
7条回答
  • 2020-12-15 16:54

    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)).")
    
    0 讨论(0)
提交回复
热议问题