Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created March 23, 2015 07:48
Show Gist options
  • Save JadenGeller/1ff15b9958400f18f2c1 to your computer and use it in GitHub Desktop.
Save JadenGeller/1ff15b9958400f18f2c1 to your computer and use it in GitHub Desktop.
Cast Int to Bool in Swift
extension Bool {
init<T : IntegerType>(_ integer: T){
self.init(integer != 0)
}
}
// Now you can do this
let x = Bool(5) // true
let y = Bool(-1) // true
let z = Bool(0) // false
@johndpope
Copy link

thanks. to be consistent with objective-c bool on negative values must return false.

@JonathanADaley
Copy link

Thanks for posting this; really great help. It allowed me to randomly initialize a boolean with arc4random_uniform( ) to use in a ternary expression.

I slightly tweaked it to make it more consistent with how ANSI C handles bools:

extension Bool {
    init<T : IntegerType>(_ integer: T) {
        if integer == 0 {
            self.init(false)
        } else {
            self.init(true)
        }
    }
}

@jimmyrogue
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment