Last active
August 29, 2015 14:02
-
-
Save kristopherjohnson/747db5ad022503ecde44 to your computer and use it in GitHub Desktop.
Null-coalescing operator for 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
// "A !|| B" returns unwrapped value of A if it is not nil, or B if it is | |
operator infix !|| { associativity left } | |
func !|| <T>(lhs: T?, rhs: T) -> T { | |
if let unwrappedValue = lhs { | |
return unwrappedValue; | |
} else { | |
return rhs; | |
} | |
} | |
let dic = [1:"One", 2:"Two", 3:"Three"] | |
dic[1] !|| "missing" // "One" | |
dic[4] !|| "missing" // "missing" | |
dic[4] !|| dic[5] !|| "missing" // "missing" | |
dic[4] !|| dic[2] !|| "missing" // "Two" | |
var x: Int? | |
x !|| 99 // 99 | |
x = 1 | |
x !|| 99 // 1 | |
x = nil | |
x !|| 99 // 99 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment