[英]How can I remove all nil elements in a Swift array?
基本方法不起作用。
for index in 0 ..< list.count {
if list[index] == nil {
list.removeAtIndex(index) //this will cause array index out of range
}
}
您的代码的问题在于0 ..< list.count
在循环开始时执行一次,此时list
仍然具有其所有元素。 每次移除一个元素, list.count
都会递减,但不会修改迭代范围。 你最终读得太远了。
在 Swift 4.1 及更高版本中,您可以使用compactMap
丢弃序列的nil
元素。 compactMap
返回非可选值的数组。
let list: [Foo?] = ...
let nonNilElements = list.compactMap { $0 }
如果你仍然想要一个可选的数组,你可以使用filter
来删除nil
元素:
list = list.filter { $0 != nil }
在 Swift 2.0 中你可以使用 flatMap:
list.flatMap { $0 }
现在在 swift 4.2 中你可以使用
list.compactMap{ $0 }
list.flatMap{ $0 }
已被弃用。
一个非常优雅的解决方案是使用由 Apple 自己制作的 Algorithms 包中定义的compacted()
。
import Algorithms
let array = [10, nil, 20, nil, 30]
print(array.compacted()) // prints [10, 20, 30]
更多信息https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.