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)
}
I recommend to set elements to nil during enumeration, and after completing remove all empty elements using arrays filter() method.
No it's not safe to mutate arrays during enumaration, your code will crash.
If you want to delete only a few objects you can use the
filter
function.In Swift 2 this is quite easy using
enumerate
andreverse
.See my swiftstub here: http://swiftstub.com/944024718/?v=beta
You might consider
filter
way:The parameter of
filter
is just a closure that takes an array type instance (in this caseString
) and returns aBool
. When the result istrue
it keeps the element, otherwise the element is filtered out.In Swift 3 and 4, this would be:
With numbers, according to Johnston's answer:
With strings as the OP's question:
However, now in Swift 4.2, there is even a better, faster way that was recommended by Apple in WWDC2018:
This new way has several advantages:
filter
.When an element at a certain index is removed from an array, all subsequent elements will have their position (and index) changed, because they shift back by one position.
So the best way is to navigate the array in reverse order - and in this case I suggest using a traditional for loop:
However in my opinion the best approach is by using the
filter
method, as described by @perlfly in his answer.