最佳答案
在 Objective-C 中,当我有一个数组时
NSArray *array;
我想检查它是否是空的,我总是这样做:
if (array.count > 0) {
NSLog(@"There are objects!");
} else {
NSLog(@"There are no objects...");
}
这样,就不需要检查 array == nil
,因为这种情况会导致代码落入 else
的情况,也可以使用非 nil
但是空数组。
然而,在 Swift 中,我偶然发现了一种情况,即我有一个可选的数组:
var array: [Int]?
我不知道该使用哪个条件,我有一些选择,比如:
选项 A: 检查同一情况下的非 nil
及空箱:
if array != nil && array!.count > 0 {
println("There are objects")
} else {
println("No objects")
}
选项 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...")
}
选项 C: 使用 Swift 提供的结合运算符:
if (array?.count ?? 0) > 0 {
println("There are objects")
} else {
println("No objects")
}
我不太喜欢 B选项,因为我在两种情况下重复代码。但是我真的不确定选项 A和 C是否正确,或者我应该使用任何其他方法来做到这一点。
我知道根据具体情况可以避免使用可选数组,但是在某些情况下,可能需要询问它是否为空。所以我想知道最简单的方法是什么。
正如@vacawama 所指出的,这种简单的检查方法是有效的:
if array?.count > 0 {
println("There are objects")
} else {
println("No objects")
}
但是,我尝试了这样一种情况,即只有在 nil
或为空时才执行特殊操作,然后不管数组是否有元素都继续执行。所以我试着:
if array?.count == 0 {
println("There are no objects")
}
// Do something regardless whether the array has elements or not.
还有
if array?.isEmpty == true {
println("There are no objects")
}
// Do something regardless whether the array has elements or not.
但是,当数组为 nil
时,它不会落入 if
体中。这是因为,在这种情况下,array?.count == nil
和 array?.isEmpty == nil
,所以表达式 array?.count == 0
和 array?.isEmpty == true
都计算为 false
。
因此,我试图找出是否有任何方法来实现这一点,只有一个条件。