Swift: delete all array elements

If you really want to clear the array, the simplest way is to Re-Initialize it.


There is a method (actually a function)

myArray.removeAll()

Taking for granted that @vadian's answer is the solution, I would just want to point out that your code doesn't work.

First of all, array indexes are 0-based, so you should rewrite the range accordingly:

for index 0..<myArray.count {
   myArray.removeAtIndex(index)
}

However this implementation is going to cause a crash. If you have an array of 10 elements, the last element occupies the position at index 9.

Using that loop, at the first iteration the element at index 0 is removed, and that causes the last element to shift down at index 8.

At the next iteration, the element at index 1 is removed, and the last element shifts down at index 7. And so on.

At some point in the loop, an attempt to remove an element for a non existing index will cause the app to crash.

When removing elements from an array in a loop, the best way of doing it is by traversing it in reverse order:

for index in reverse(0..<myArray.count) {
    myArray.removeAtIndex(index)
}

That ensures that removed elements don't change the order or the index of the elements still to be processed.

Tags:

Ios

Swift