检查可选数组是否为空 [英] Check if optional array is empty

查看:46
本文介绍了检查可选数组是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 > 0) {
    NSLog(@"There are objects!");
} else {
    NSLog(@"There are no objects...");
}

这样就不用检查是否array == nil,因为这种情况会导致代码陷入else的情况,以及非-nil 但空数组就可以了.

That way, there is no need to check if array == nil since this situation will lead the code to fall into the else case, as well as a non-nil but empty array would do.

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

However, in Swift, I have stumbled across the situation in which I have an optional array:

var array: [Int]?

而且我无法弄清楚要使用哪个条件.我有一些选择,例如:

and I am not being able to figure out which condition to use. I have some options, like:

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

Option A: Check both non-nil and empty cases in the same condition:

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

选项 B: 使用 let 取消绑定数组:

Option B: Unbind the array using 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 提供的合并运算符:

Option C: Using the coalescing operator that Swift provides:

if (array?.count ?? 0) > 0 {
    println("There are objects")
} else {
    println("No objects")
}

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

I do not like the option B very much, because I am repeating code in two conditions. But I am not really sure about whether options A and C are correct or I should use any other way of doing this.

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

I know that the use of an optional array could be avoided depending on the situation, but in some case it could be necessary to ask if it is empty. So I would like to know what is the way to do it the simplest way.

<小时>

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

As @vacawama pointed out, this simple way of checking it works:

if array?.count > 0 {
    println("There are objects")
} else {
    println("No objects")
}

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

However, I was trying the case in which I want to do something special only when it is nil or empty, and then continue regardless whether the array has elements or not. So I tried:

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 == nilarray?.isEmpty == nil,所以表达式 array?.count == 0array?.isEmpty == true 都计算为 false.

But, when array is nil, it does not fall into the if body. And this is because, in that case, array?.count == nil and array?.isEmpty == nil, so the expressions array?.count == 0 and array?.isEmpty == true both evaluate to false.

所以我想弄清楚是否有任何方法可以只用一个条件来实现这一点.

So I am trying to figure out if there is any way of achieve this with just one condition as well.

推荐答案

更新了 Swift 3 及更高版本的答案:

Swift 3 取消了将选项与 >< 进行比较的功能,因此之前答案的某些部分不再有效.

Updated answer for Swift 3 and above:

Swift 3 has removed the ability to compare optionals with > and <, so some parts of the previous answer are no longer valid.

仍然可以用 == 来比较可选项,所以检查一个可选项数组是否包含值的最直接的方法是:

It is still possible to compare optionals with ==, so the most straightforward way to check if an optional array contains values is:

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

其他方法:

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!")
}


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


If you want to do something when the array is nil or is empty, you have at least 6 choices:

选项 A:

if !(array?.isEmpty == false) {
    print("There are no objects")
}

选项 B:

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

选项 C:

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

选项 D:

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

选项 E:

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

选项 F:

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

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

Option C exactly captures how you described it in English: "I want to do something special only when it is nil or empty." I would recommend that you use this since it is easy to understand. There is nothing wrong with this, especially since it will "short circuit" and skip the check for empty if the variable is nil.

你可以简单地:

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

正如@Martin 在评论中指出的那样,它使用 func >(lhs: T?, rhs: T?) ->Bool 表示编译器将 0 包装为 Int? 以便可以与左侧的 Int? 因为可选的链接调用.

As @Martin points out in the comments, it uses func ><T : _Comparable>(lhs: T?, rhs: T?) -> Bool which means that the compiler wraps 0 as an Int? so that the comparison can be made with the left hand side which is an Int? because of the optional chaining call.

以类似的方式,您可以:

In a similar way, you could do:

if array?.isEmpty == false {
    print("There are objects")
} else {
    print("No objects")
}

注意:您必须在此处明确与 false 进行比较才能使其正常工作.

Note: You have to explicitly compare with false here for this to work.

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

If you want to do something when the array is nil or is empty, you have at least 7 choices:

选项 A:

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

选项 B:

if !(array?.isEmpty == false) {
    print("There are no objects")
}

选项 C:

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

选项 D:

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

选项 E:

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

选项 F:

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

选项 G:

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

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

Option D exactly captures how you described it in English: "I want to do something special only when it is nil or empty." I would recommend that you use this since it is easy to understand. There is nothing wrong with this, especially since it will "short circuit" and skip the check for empty if the variable is nil.

这篇关于检查可选数组是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆