Skip to content

Instantly share code, notes, and snippets.

@vfn
Created November 6, 2019 23:15
Show Gist options
  • Save vfn/e539ad6904f1f2eedb80f8134326052d to your computer and use it in GitHub Desktop.
Save vfn/e539ad6904f1f2eedb80f8134326052d to your computer and use it in GitHub Desktop.
Swift utils
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