Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment