In Objective-C, when I have an array
NSArray *array;
and I want to check if it is not empty, I always do:
if (array.count &
Swift 3-4 compatible:
extension Optional where Wrapped: Collection {
var nilIfEmpty: Optional {
switch self {
case .some(let collection):
return collection.isEmpty ? nil : collection
default:
return nil
}
}
var isNilOrEmpty: Bool {
switch self {
case .some(let collection):
return collection.isEmpty
case .none:
return true
}
}
Usage:
guard let array = myObject?.array.nilIfEmpty else { return }
Or
if myObject.array.isNilOrEmpty {
// Do stuff here
}