TIMEX TIMEX - 5 months ago 21x
Swift Question

How can I remove all nil elements in a Swift array?

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


Use filter to filter out nil elements:

list = list.filter { $0 != nil }

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.

EDIT Removed the C-style loop because it's incorrect (for reasons other than @MartinR pointed out before deleting his comment, but incorrect nonetheless).

EDIT 2 Now that Swift has flatMap, Marcel Molina's answer is better.