Last active
March 12, 2018 18:23
-
-
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.
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
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