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
How can I remove all nil elements in a Swift array?
提问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.count
is executed once at the beginning of the loop, when list
still has all of its elements. Each time you remove one element, list.count
is 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 compactMap
to discard the nil
elements of a sequence. compactMap
returns 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 filter
to remove nil
elements:
如果你仍然想要一个可选的数组,你可以使用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 } 已被弃用。