Created
February 23, 2016 16:41
-
-
Save cdzombak/0908f1437ceb5bad7a51 to your computer and use it in GitHub Desktop.
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
let nilString: String? = nil | |
let aString: String? = "a non-nil string" | |
print (nilString ?? "the string is nil") | |
print (aString ?? "the string is nil") | |
// if you don't want to use `??` … | |
// (inspired by Scala's Option's `getOrElse`) | |
extension Optional { | |
func or(ifNil: Wrapped) -> Wrapped { | |
switch self { | |
case .None: | |
return ifNil | |
case let .Some(wrappedValue): | |
return wrappedValue | |
} | |
} | |
} | |
print(nilString.or("the string is nil")) // "the string is nil" | |
print(aString.or("the string is nil")) // "a non-nil string" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment