Last active
November 12, 2021 08:10
-
-
Save casperzandbergenyaacomm/b01672a2d4b259cde65a8ad643131c60 to your computer and use it in GitHub Desktop.
Adding readability for an if statement I often use.
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
protocol EmptyOrNil { | |
var isEmpty: Bool { get } | |
} | |
extension Optional where Wrapped: EmptyOrNil { | |
var isEmptyOrNil: Bool { | |
return self?.isEmpty ?? true | |
} | |
} | |
// Any type that has or can implement isEmpty | |
extension String: EmptyOrNil { } | |
extension Array: EmptyOrNil { } | |
extension Dictionary: EmptyOrNil where Key: Hashable { } | |
// ... | |
/* ------------------------------------------------------------------ */ | |
// Example usage | |
// Before: | |
var optionalString: String? | |
if optionalString?.isEmpty ?? true { | |
// String doesnt contain anything | |
} | |
// After: | |
var optionalArray: Array<Any>? | |
if optionalArray.isEmptyOrNil { | |
// Array doesnt contain anything | |
} | |
// You could even argue that | |
guard !data.isEmptyOrNil else { return } | |
data!.doSomething | |
// is more readable than | |
guard let data = data, !data.isEmpty else { return } | |
data.doSomething |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Somehow Xcode 10 shows me multiple isEmpty completions when I do this.