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
}
}
2 个解决方案
#1
59
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。 <列表。count在循环开始时执行一次,此时list仍然拥有它的所有元素。每次移除一个元素时,列出。计数是递减的,但是迭代范围没有被修改。你最后读得太深了。< p>
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 { $0 }
In Swift 2 to and including 4.0, use flatMap
. flatMap
does the same thing:
在Swift 2至4.0中,使用平面地图。flatMap做同样的事情:
let list: [Foo?] = ...
let nonNilElements = list.flatMap { $0 }
If you still want an array of optionals, or if you're still using Swift 1, you can use filter
to remove nil
elements:
如果你还想要一个选项数组,或者你还在使用Swift 1,你可以使用filter来删除nil元素:
list = list.filter { $0 != nil }
#2
70
In Swift 2.0 you can use flatMap:
在Swift 2.0中,可以使用flatMap:
list.flatMap { $0 }
#1
59
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。 <列表。count在循环开始时执行一次,此时list仍然拥有它的所有元素。每次移除一个元素时,列出。计数是递减的,但是迭代范围没有被修改。你最后读得太深了。< p>
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 { $0 }
In Swift 2 to and including 4.0, use flatMap
. flatMap
does the same thing:
在Swift 2至4.0中,使用平面地图。flatMap做同样的事情:
let list: [Foo?] = ...
let nonNilElements = list.flatMap { $0 }
If you still want an array of optionals, or if you're still using Swift 1, you can use filter
to remove nil
elements:
如果你还想要一个选项数组,或者你还在使用Swift 1,你可以使用filter来删除nil元素:
list = list.filter { $0 != nil }
#2
70
In Swift 2.0 you can use flatMap:
在Swift 2.0中,可以使用flatMap:
list.flatMap { $0 }