Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.