基本方法行不通.
for index in 0 ..< list.count {
if list[index] == nil {
list.removeAtIndex(index) //this will cause array index out of range
}
}
基本方法行不通.
for index in 0 ..< list.count {
if list[index] == nil {
list.removeAtIndex(index) //this will cause array index out of range
}
}
您的代码的问题在于,当list
仍然具有其所有元素时,0 ..< list.count
在循环开始时执行一次.每次删除一个元素时,list.count
都会递减,但迭代范围不会修改.你最终会读得太多.
在Swift 4.1及以上版本中,可以使用compactMap
来丢弃序列中的nil
个元素.compactMap
返回非可选值的array.
let list: [Foo?] = ...
let nonNilElements = list.compactMap { $0 }
如果您仍然需要一个选项数组,可以使用filter
删除nil
个元素:
list = list.filter { $0 != nil }