Removing from array during enumeration in Swift?

Andrew picture Andrew · Feb 4, 2015 · Viewed 32.1k times · Source

I want to enumerate through an array in Swift, and remove certain items. I'm wondering if this is safe to do, and if not, how I'm supposed to achieve this.

Currently, I'd be doing this:

for (index, aString: String) in enumerate(array) {
    //Some of the strings...
    array.removeAtIndex(index)
}

Answer

Johnston picture Johnston · Oct 14, 2015

In Swift 2 this is quite easy using enumerate and reverse.

var a = [1,2,3,4,5,6]
for (i,num) in a.enumerate().reverse() {
    a.removeAtIndex(i)
}
print(a)