Skip to content

Instantly share code, notes, and snippets.

@casperzandbergenyaacomm
Last active November 12, 2021 08:10
Show Gist options
  • Save casperzandbergenyaacomm/b01672a2d4b259cde65a8ad643131c60 to your computer and use it in GitHub Desktop.
Save casperzandbergenyaacomm/b01672a2d4b259cde65a8ad643131c60 to your computer and use it in GitHub Desktop.
Adding readability for an if statement I often use.
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
@casperzandbergenyaacomm
Copy link
Author

Somehow Xcode 10 shows me multiple isEmpty completions when I do this.

image

@Amzd
Copy link

Amzd commented Nov 12, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment