× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Swift: delete all array elements

Antonio Bello
Jul 06, 2015
<p>Taking for granted that @vadian's answer <strong>is the solution</strong>, I would just want to point out that your code doesn't work.</p> <p>First of all, array indexes are 0-based, so you should rewrite the range accordingly:</p> <pre><code>for index 0..&lt;myArray.count { myArray.removeAtIndex(index) } </code></pre> <p>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. </p> <p>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.</p> <p>At the next iteration, the element at index 1 is removed, and the last element shifts down at index 7. And so on.</p> <p>At some point in the loop, an attempt to remove an element for a non existing index will cause the app to crash.</p> <p>When removing elements from an array in a loop, the best way of doing it is by traversing it in reverse order:</p> <pre><code>for index in reverse(0..&lt;myArray.count) { myArray.removeAtIndex(index) } </code></pre> <p>That ensures that removed elements don't change the order or the index of the elements still to be processed.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31183431/Swift:%20delete%20all%20array%20elements/31184048">Stack Overflow</a>.</p>
comments powered by Disqus