Skip to content

Instantly share code, notes, and snippets.

@cdzombak
Created February 23, 2016 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdzombak/0908f1437ceb5bad7a51 to your computer and use it in GitHub Desktop.
Save cdzombak/0908f1437ceb5bad7a51 to your computer and use it in GitHub Desktop.
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