检查可选数组是否为空

eze*_*uli 66 arrays ios swift

在Objective-C中,当我有一个数组

NSArray *array;
Run Code Online (Sandbox Code Playgroud)

我想检查它是否为空,我总是这样做:

if (array.count > 0) {
    NSLog(@"There are objects!");
} else {
    NSLog(@"There are no objects...");
}
Run Code Online (Sandbox Code Playgroud)

这样,就没有必要检查是否array == nil因为这种情况会导致代码陷入这种else情况,以及非nil空数组也会这样做.

但是,在Swift中,我偶然发现了我有一个可选数组的情况:

var array: [Int]?
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚使用哪种条件.我有一些选择,比如:

选项A:nil在相同条件下检查非案例和空案例:

if array != nil && array!.count > 0 {
    println("There are objects")
} else {
    println("No objects")
}
Run Code Online (Sandbox Code Playgroud)

选项B:使用let以下方法取消绑定数组:

if let unbindArray = array {
    if (unbindArray.count > 0) {
        println("There are objects!")
    } else {
        println("There are no objects...")
    }
} else {
    println("There are no objects...")
}
Run Code Online (Sandbox Code Playgroud)

选项C:使用Swift提供的合并运算符:

if (array?.count ?? 0) > 0 {
    println("There are objects")
} else {
    println("No objects")
}
Run Code Online (Sandbox Code Playgroud)

我非常不喜欢选项B,因为我在两个条件下重复代码.但我不确定选项AC是否正确或我应该使用任何其他方式来做到这一点.

我知道可以根据情况避免使用可选数组,但在某些情况下可能需要询问它是否为空.所以我想知道最简单的方法是什么.


编辑:

正如@vacawama所指出的,这种简单的检查方式有效:

if array?.count > 0 {
    println("There are objects")
} else {
    println("No objects")
}
Run Code Online (Sandbox Code Playgroud)

但是,我正在尝试这样一种情况,我只想在它是nil空的时候做一些特殊的事情,然后继续,无论数组是否有元素.所以我尝试过:

if array?.count == 0 {
    println("There are no objects")
}

// Do something regardless whether the array has elements or not.
Run Code Online (Sandbox Code Playgroud)

并且

if array?.isEmpty == true {
    println("There are no objects")
}

// Do something regardless whether the array has elements or not.
Run Code Online (Sandbox Code Playgroud)

但是,当阵列出现时nil,它不会落入if体内.这是因为,在这种情况下,array?.count == nilarray?.isEmpty == nil,这样的表达array?.count == 0,并array?.isEmpty == true这两个评估到false.

所以我试图找出是否有任何方法可以实现这一点,只有一个条件.

vac*_*ama 128

更新了Swift 3的答案:

Swift 3删除了使用>和比较选项的能力<,因此前一个答案的某些部分不再有效.

仍然可以比较选项==,因此检查可选数组是否包含值的最直接方法是:

if array?.isEmpty == false {
    print("There are objects!")
}
Run Code Online (Sandbox Code Playgroud)

其他方式可以做到:

if array?.count ?? 0 > 0 {
    print("There are objects!")
}

if !(array?.isEmpty ?? true) {
    print("There are objects!")
}

if array != nil && !array!.isEmpty {
    print("There are objects!")
}

if array != nil && array!.count > 0 {
    print("There are objects!")
}

if !(array ?? []).isEmpty {
    print("There are objects!")
}

if (array ?? []).count > 0 {
    print("There are objects!")
}

if let array = array, array.count > 0 {
    print("There are objects!")
}

if let array = array, !array.isEmpty {
    print("There are objects!")
}
Run Code Online (Sandbox Code Playgroud)

如果你想在数组nil是空的时候做某事,你至少有6个选择:

选项A:

if !(array?.isEmpty == false) {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项B:

if array == nil || array!.count == 0 {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项C:

if array == nil || array!.isEmpty {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项D:

if (array ?? []).isEmpty {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项E:

if array?.isEmpty ?? true {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项F:

if (array?.count ?? 0) == 0 {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项C完全捕捉到你用英语描述它的方式:"我想只在它为零或空时才做一些特殊的事情." 我建议您使用它,因为它很容易理解.这没有任何问题,特别是因为它会"短路"并且如果变量是空的则跳过检查为空nil.



Swift 2.x的上一个答案:

你可以简单地做:

if array?.count > 0 {
    print("There are objects")
} else {
    print("No objects")
}
Run Code Online (Sandbox Code Playgroud)

正如@Martin在评论中指出的那样,它使用的func ><T : _Comparable>(lhs: T?, rhs: T?) -> Bool意思是编译器包装0为一个,Int?以便可以与左侧进行比较,这是Int?因为可选的链接调用.

以类似的方式,您可以:

if array?.isEmpty == false {
    print("There are objects")
} else {
    print("No objects")
}
Run Code Online (Sandbox Code Playgroud)

注意:您必须明确地与false此处进行比较才能实现此目的.


如果你想在数组是nil或为空时做某事,你至少有7个选择:

选项A:

if !(array?.count > 0) {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项B:

if !(array?.isEmpty == false) {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项C:

if array == nil || array!.count == 0 {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项D:

if array == nil || array!.isEmpty {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项E:

if (array ?? []).isEmpty {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项F:

if array?.isEmpty ?? true {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项G:

if (array?.count ?? 0) == 0 {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)

选项D完全捕捉到你用英语描述它的方式:"我想只在零或空时做一些特别的事情." 我建议您使用它,因为它很容易理解.这没有任何问题,特别是因为它会"短路"并且如果变量是空的则跳过检查为空nil.

  • 这有效.只是为了完整性:它使用`func> <T:_Comparable>(lhs:T?,rhs:T?) - > Bool`运算符,右侧`0`被包装到`Int?`中编译器. (2认同)
  • @Rambatino,`!(array?.isEmpty == false)`如果`array`是`nil`将是`true`,但是`array` .isEmpty == true`如果'array`是``将是`false` nil`因为`nil`不等于`true`.我们想把一个`nil``数组`视为空. (2认同)

Mob*_*Dan 7

Collection议定书的延伸财产

*用Swift 3编写

extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        switch self {
            case .some(let collection):
                return collection.isEmpty
            case .none:
                return true
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例使用:

if array.isNilOrEmpty {
    print("The array is nil or empty")
}
Run Code Online (Sandbox Code Playgroud)

 

其他选择

除了上面的扩展,我发现以下选项最明显,没有强制解包选项.我读这是解开可选数组,如果是nil,则替换相同类型的空数组.然后,取其(非可选)结果并isEmpty执行条件代码.

推荐的

if (array ?? []).isEmpty {
    print("The array is nil or empty")
}
Run Code Online (Sandbox Code Playgroud)

虽然以下内容清楚地表明,但我建议尽可能避免使用力量展开选项.虽然你是保证array将永远不会被nilarray!.isEmpty在这种特殊情况下执行,这将是便于以后编辑并无意中引入崩溃.当你变得很舒服地展开选项时,你会增加某人在将来编译但在运行时崩溃的可能性.

不建议!

if array == nil || array!.isEmpty {
    print("The array is nil or empty")
}
Run Code Online (Sandbox Code Playgroud)

我发现包括array?(可选链接)混淆的选项如:

混乱?

if !(array?.isEmpty == false) {
    print("The array is nil or empty")
}

if array?.isEmpty ?? true {
    print("There are no objects")
}
Run Code Online (Sandbox Code Playgroud)


Leo*_*Leo 6

Swift 3-4 兼容:

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
        }
}
Run Code Online (Sandbox Code Playgroud)

用法:

guard let array = myObject?.array.nilIfEmpty else { return }
Run Code Online (Sandbox Code Playgroud)

或者

if myObject.array.isNilOrEmpty {
    // Do stuff here
}
Run Code Online (Sandbox Code Playgroud)


jrt*_*ton 5

选项D:如果数组不需要是可选的,因为您只关心它是否为空,请将其初始化为空数组而不是可选:

var array = [Int]()
Run Code Online (Sandbox Code Playgroud)

现在它将永远存在,你可以简单地检查isEmpty.