Skip to content

Instantly share code, notes, and snippets.

@ijoshsmith
Last active August 29, 2015 14:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijoshsmith/0107e7c2942bdac73e5c to your computer and use it in GitHub Desktop.
Save ijoshsmith/0107e7c2942bdac73e5c to your computer and use it in GitHub Desktop.
Nil-coalescing Operator in Swift
//
// 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