Skip to content

Instantly share code, notes, and snippets.

@Amzd
Forked from casperzandbergenyaacomm/EmptyOrNil.swift
Last active June 10, 2024 13:48
Show Gist options
  • Save Amzd/d917247df7a281ae1896c3d7f9a23527 to your computer and use it in GitHub Desktop.
Save Amzd/d917247df7a281ae1896c3d7f9a23527 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment