ios 如何删除 Swift 数组中的所有 nil 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31571570/
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 06:57:46  来源:igfitidea点击:

How can I remove all nil elements in a Swift array?

iosswift

提问by TIMEX

Basic way doesn't work.

基本方法不起作用。

for index in 0 ..< list.count {
    if list[index] == nil {
        list.removeAtIndex(index) //this will cause array index out of range
    }
}

回答by zneak

The problem with your code is that 0 ..< list.countis executed once at the beginning of the loop, when liststill has all of its elements. Each time you remove one element, list.countis decremented, but the iteration range is not modified. You end up reading too far.

您的代码的问题是0 ..< list.count在循环开始时执行一次,此时list仍然具有其所有元素。每次删除一个元素,list.count递减,但迭代范围不修改。你最终读得太远了。

In Swift 4.1 and above, you can use compactMapto discard the nilelements of a sequence. compactMapreturns an array of non-optional values.

在 Swift 4.1 及更高版本中,您可以使用compactMap丢弃nil序列的元素。compactMap返回一组非可选值。

let list: [Foo?] = ...
let nonNilElements = list.compactMap { 
list = list.filter { 
list.flatMap { 
list.compactMap{ ##代码## }
}
!= nil }
}

If you still want an array of optionals, you can use filterto remove nilelements:

如果你仍然想要一个可选的数组,你可以使用filter删除nil元素:

##代码##

回答by Marcel Molina

In Swift 2.0 you can use flatMap:

在 Swift 2.0 中你可以使用 flatMap:

##代码##

回答by kalafun

Now in swift 4.2 you can use

现在在 swift 4.2 中你可以使用

##代码##
  • list.flatMap { $0 } is already deprecated.
  • list.flatMap { $0 } 已被弃用。