Created
March 23, 2015 07:48
-
-
Save JadenGeller/1ff15b9958400f18f2c1 to your computer and use it in GitHub Desktop.
Cast Int to Bool in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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)
}
}
}
Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks. to be consistent with objective-c bool on negative values must return false.