Skip to content

Instantly share code, notes, and snippets.

@amlcurran
Created September 4, 2016 21:32
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 amlcurran/0e4806c355ca235d3aa2b47280c1da16 to your computer and use it in GitHub Desktop.
Save amlcurran/0e4806c355ca235d3aa2b47280c1da16 to your computer and use it in GitHub Desktop.
Some fluent wrappers around the nil-coalescing operator and optionals in Swift
extension Optional {
func or(_ backup: Wrapped) -> Wrapped {
if let wrapped = self {
return wrapped
}
return backup
}
}
extension Optional where Wrapped: ExpressibleByArrayLiteral {
func orEmpty() -> Wrapped {
let emptyArray: Wrapped = []
return or(emptyArray)
}
}
let string: String? = nil
string.or("alternative").utf8.count // returns 11
let array: [String]? = nil
array.orEmpty().count // returns 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment