Last active
August 29, 2015 14:04
-
-
Save ijoshsmith/0107e7c2942bdac73e5c to your computer and use it in GitHub Desktop.
Nil-coalescing Operator in Swift
This file contains hidden or 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
// | |
// UPDATE: This gist was rendered obsolete as of | |
// Xcode 6 Beta 5, which introduced the nil | |
// coalescing operator in Swift proper (??). | |
// | |
/* Nil-coalescing operator */ | |
infix operator !! {} | |
func !! <T> ( | |
value: T?, | |
defaultValue: @auto_closure () -> T) | |
-> T | |
{ | |
return value ? value! : defaultValue() | |
} | |
let text = "13" | |
let number = text.toInt() !! 0 | |
println(number) | |
// prints: 13 | |
println("word".toInt() !! 99 + 1) | |
// prints: 100 | |
// Prints a message to show when it executes. | |
func getDefaultNumber() -> Int | |
{ | |
print("Getting the default number…") | |
return -1 | |
} | |
println("42".toInt() !! getDefaultNumber()) | |
// prints: 42 | |
println("Josh".toInt() !! getDefaultNumber()) | |
// prints: Getting the default number…-1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment