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