ios 检查可选数组是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27588964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:05:00  来源:igfitidea点击:

Check if optional array is empty

iosarraysswift

提问by eze.scaruli

In Objective-C, when I have an array

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

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...");
}

That way, there is no need to check if array == nilsince this situation will lead the code to fall into the elsecase, as well as a non-nilbut empty array would do.

这样,就没有必要检查是否array == nil因为这种情况会导致代码陷入这种else情况,而一个非但nil空的数组也会这样做。

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

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

var array: [Int]?

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

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

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

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

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

Option B:Unbind the array using let:

选项 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...")
}

Option C:Using the coalescing operator that Swift provides:

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

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

I do not like the option Bvery much, because I am repeating code in two conditions. But I am not really sure about whether options Aand Care correct or I should use any other way of doing this.

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

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.

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



EDIT:编辑:

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

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

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

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

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

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

// Do something regardless whether the array has elements or not.

And also

并且

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

// Do something regardless whether the array has elements or not.

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

但是,当 array is 时nil,它不会落入if主体。这是因为,在那种情况下,array?.count == niland array?.isEmpty == nil,所以表达式array?.count == 0array?.isEmpty == true都计算为false

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

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

回答by vacawama

Updated answer for Swift 3 and above:

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

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

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

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

Other ways it can be done:

其他方法可以做到:

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


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

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

Option A:

选项A:

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

Option B:

选项 B:

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

Option C:

选项 C:

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

Option D:

选项 D:

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

Option E:

选项 E:

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

Option F:

选项 F:

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

Option Cexactly 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.

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





Previous answer for Swift 2.x:

Swift 2.x 的上一个答案:

You can simply do:

你可以简单地做:

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

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

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

In a similar way, you could do:

以类似的方式,您可以执行以下操作:

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

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

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



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

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

Option A:

选项A:

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

Option B:

选项 B:

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

Option C:

选项 C:

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

Option D:

选项 D:

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

Option E:

选项 E:

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

Option F:

选项 F:

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

Option G:

选项 G:

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

Option Dexactly 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.

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

回答by Mobile Dan

Extension Property on the CollectionProtocol

Collection协议上的扩展属性

*Written in Swift 3

*用 Swift 3 编写

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

Example Use:

使用示例:

if array.isNilOrEmpty {
    print("The array is nil or empty")
}

 

 

Other Options

其他选项

Other than the extension above, I find the following option most clear without force unwrapping optionals. I read this as unwrapping the optional array and if nil, substituting an empty array of the same type. Then, taking the (non-optional) result of that and if it isEmptyexecute the conditional code.

除了上面的扩展之外,我发现以下选项最清晰,无需强制展开选项。我将其读作解包可选数组,如果为 nil,则替换为相同类型的空数组。然后,取其(非可选)结果并isEmpty执行条件代码。

Recommended

受到推崇的

if (array ?? []).isEmpty {
    print("The array is nil or empty")
}

Though the following reads clearly, I suggest a habit of avoiding force unwrapping optionals whenever possible. Though you are guaranteed that arraywill never be nilwhen array!.isEmptyis executed in this specific case, it would be easy to edit it later and inadvertently introduce a crash. When you become comfortable force unwrapping optionals, you increase the chance that someone will make a change in the future that compiles but crashes at runtime.

尽管下面的内容读起来很清楚,但我建议养成尽可能避免强制展开可选项的习惯。虽然你是保证array绝不会nilarray!.isEmpty这个特定的情况下被执行,这将在以后很容易编辑和无意中引入崩溃。当您习惯强制解包可选项时,您会增加将来有人进行更改的可能性,该更改可以编译但在运行时崩溃。

Not Recommended!

不建议!

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

I find options that include array?(optional chaining) confusing such as:

我发现包含array?(可选链接)的选项令人困惑,例如:

Confusing?

令人困惑?

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

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

回答by Leo

Swift 3-4 compatible:

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
        }
}

Usage:

用法:

guard let array = myObject?.array.nilIfEmpty else { return }

Or

或者

if myObject.array.isNilOrEmpty {
    // Do stuff here
}

回答by jrturton

Option D:If the array doesn't need to be optional, because you only really care if it's empty or not, initialise it as an empty array instead of an optional:

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

var array = [Int]()

Now it will always exist, and you can simply check for isEmpty.

现在它将始终存在,您只需检查isEmpty.

回答by borchero

Conditional unwrapping:

条件解包:

if let anArray = array {
    if !anArray.isEmpty {
        //do something
    }
}

EDIT: Possible since Swift 1.2:

编辑:自 Swift 1.2 起可能:

if let myArray = array where !myArray.isEmpty {
    // do something with non empty 'myArray'
}

EDIT: Possible since Swift 2.0:

编辑:自 Swift 2.0 起可能:

guard let myArray = array where !myArray.isEmpty else {
    return
}
// do something with non empty 'myArray'

回答by matt

The elegant built-in solution is Optional's mapmethod. This method is often forgotten, but it does exactly what you need here; it allows you to send a message to the thing wrapped inside an Optional, safely. We end up in this case with a kind of threeway switch: we can say isEmptyto the Optional array, and get true, false, or nil (in case the array is itself nil).

优雅的内置解决方案是 Optional 的map方法。这种方法经常被遗忘,但它正是您在这里需要的;它允许您安全地向包裹在 Optional 中的事物发送消息。在这种情况下,我们以一种三路开关结束:我们可以isEmpty对 Optional 数组说,并得到 true、false 或 nil(如果数组本身是 nil)。

var array : [Int]?
array.map {
guard !array.isEmpty else {
    return
}
// do something with non empty ‘array'
.isEmpty} // nil (because `array` is nil) array = [] array.map {##代码##.isEmpty} // true (wrapped in an Optional) array?.append(1) array.map {##代码##.isEmpty} // false (wrapped in an Optional)

回答by Phil

Instead of using ifand elseit is better way just to use guardto check for empty array without creating new variables for the same array.

而不是使用if并且else更好的方法是使用guard检查空数组而不为同一数组创建新变量。

##代码##