Check if optional array is empty

后端 未结 7 2214
感情败类
感情败类 2020-11-29 18:21

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 &         


        
相关标签:
7条回答
  • 2020-11-29 19:06

    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
    }
    
    0 讨论(0)
提交回复
热议问题