Converting Boolean value to Integer value in swift 3

前端 未结 7 902
予麋鹿
予麋鹿 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:31

    Swift 5

    Bool -> Int

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

    Int -> Bool

    extension Int {
        var boolValue: Bool {
            return self != 0 
        }
    }
    
    0 讨论(0)
  • 2020-12-15 16:33

    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))   
    
    0 讨论(0)
  • 2020-12-15 16:38

    You could use hashValue property:

    let active = true
    active.hashValue // returns 1
    active = false
    active.hashValue // returns 0
    
    0 讨论(0)
  • 2020-12-15 16:43

    let boolAsInt = <#your bool#> ? 1 : 0

    0 讨论(0)
  • 2020-12-15 16:52

    Try this,

    let p1 = ("a" == "a") //true
    print(true)           //"true\n"
    print(p1)             //"true\n"
    
    Int(true)             //1
    
    Int(NSNumber(value:p1)) //1
    
    0 讨论(0)
  • 2020-12-15 16:53

    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.

    0 讨论(0)
提交回复
热议问题