基本方式不起作用.
for index in 0 ..< list.count {
if list[index] == nil {
list.removeAtIndex(index) //this will cause array index out of range
}
}
Run Code Online (Sandbox Code Playgroud)
zne*_*eak 109
您的代码的问题是0 ..< list.count在循环开始时执行一次,当时list仍然包含其所有元素.每次删除一个元素时,list.count都会递减,但迭代范围不会被修改.你最终读得太远了.
在Swift 4.1及更高版本中,您可以使用compactMap丢弃nil序列的元素.compactMap返回一组非可选值.
let list: [Foo?] = ...
let nonNilElements = list.compactMap { $0 }
Run Code Online (Sandbox Code Playgroud)
在Swift 2中包括4.0,使用filter.nil做同样的事情:
list = list.filter { $0 != nil }
Run Code Online (Sandbox Code Playgroud)
如果你仍然想要一个选项数组,或者你还在使用Swift 1,你可以使用0 ..< list.count删除list元素:
let list: [Foo?] = ...
let nonNilElements = list.compactMap { $0 }
Run Code Online (Sandbox Code Playgroud)
Mar*_*ina 75
在Swift 2.0中,您可以使用flatMap:
list.flatMap { $0 }
Run Code Online (Sandbox Code Playgroud)
kal*_*fun 16
现在在Swift 4.2中,您可以使用
list.compactMap{ $0 }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25514 次 |
| 最近记录: |