Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Last active March 12, 2018 18:23
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 jakehawken/016e6a87c7f8e58e66d20e2ee99280f4 to your computer and use it in GitHub Desktop.
Save jakehawken/016e6a87c7f8e58e66d20e2ee99280f4 to your computer and use it in GitHub Desktop.
I have wanted this method to exist since Swift 1. I realized this morning that there was no reason that it couldn't.
extension Optional where Wrapped: Collection {
/*
NOTE: Since this extends Optional rather than the possible collection,
you don't use the "?" when calling it `isEmptyOrNil()`
Example:
var myString: String? = ""
myString.isEmptyOrNil // Evaluates to true.
myString = nil
myString.isEmptyOrNil // Also evaluates to true.
myString?.isEmptyOrNil // Will not compile.
*/
var isEmptyOrNil: Bool {
switch self {
case .some(let collection):
return collection.isEmpty
case .none:
return true
}
}
/*
This allows you to use nil coalescing to on a string, whether it's nil or just empty.
Example:
var myString: String? = ""
var nonNilString: String = myString.nilIfEmpty() ?? "WOOT" // nonNilString will equal "WOOT"
myString = nil
nonNilString: String = myString.nilIfEmpty() ?? "NEATO" // nonNilString will equal "NEATO"
*/
func nilIfEmpty() -> Wrapped? {
return isEmptyOrNil ? nil : self!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment