Created
November 6, 2019 23:15
-
-
Save vfn/e539ad6904f1f2eedb80f8134326052d to your computer and use it in GitHub Desktop.
Swift utils
This file contains hidden or 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
public protocol CanBeEmpty { | |
var isEmpty: Bool { get } | |
var isNotEmpty: Bool { get } | |
var nilIfEmpty: Self? { get } | |
} | |
public extension CanBeEmpty { | |
/// Returns nil if empty, otherwise returns self | |
var nilIfEmpty: Self? { return self.isEmpty ? nil : self } | |
/// A Boolean value that indicates whether the collection is not empty. | |
var isNotEmpty: Bool { return !self.isEmpty } | |
} | |
extension String: CanBeEmpty {} | |
extension Array: CanBeEmpty {} | |
extension Set: CanBeEmpty {} | |
extension Dictionary: CanBeEmpty {} | |
public extension Optional where Wrapped: CanBeEmpty { | |
/// Returns whether self is nil or the unwrapped collection is empty | |
var isNilOrEmpty: Bool { return self.flatMap({ $0.isEmpty }) ?? true } | |
/// Returns whether the unwrapped collection is not empty | |
var isNotEmpty: Bool { return !self.isNilOrEmpty } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment