TIMEX TIMEX - 1 year ago 116
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download