Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active August 29, 2015 14:02
Show Gist options
  • Save kristopherjohnson/747db5ad022503ecde44 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/747db5ad022503ecde44 to your computer and use it in GitHub Desktop.
Null-coalescing operator for Swift
// "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