Swift: delete all array elements
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.
If you really want to clear the array, the simplest way is to Re-Initialize it.
You're missing the in
keyword which is causing your error. The code should be:
for index in 1...myArray.count {
myArray.removeAtIndex(index)
}
This will however not work as you would expect for a couple of reasons:
- The last valid index is
count - 1
which would require1..<myArray.count
- More importantly removing an element from an array shortens it thus changing the indexes each time.
If you're trying to remove all things from the array then you should do as others have suggested and use:
myArray.removeAll()
In the case that you do only want the first element and nothing else you could get a reference to the first object, empty the array, then add the object back on:
var firstElement = myArray.first!
myArray.removeAll()
myArray.append(firstElement)