Removing from array during enumeration in Swift?
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)
You might consider filter
way:
var theStrings = ["foo", "bar", "zxy"]// Filter only strings that begins with "b"theStrings = theStrings.filter { $0.hasPrefix("b") }
The parameter of filter
is just a closure that takes an array type instance (in this case String
) and returns a Bool
. When the result is true
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:
var a = [1,2,3,4,5,6]for (i,num) in a.enumerated().reversed() { a.remove(at: i)}print(a)
With strings as the OP's question:
var b = ["a", "b", "c", "d", "e", "f"]for (i,str) in b.enumerated().reversed(){ if str == "c" { b.remove(at: i) }}print(b)
However, now in Swift 4.2 or later, there is even a better, faster way that was recommended by Apple in WWDC2018:
var c = ["a", "b", "c", "d", "e", "f"]c.removeAll(where: {$0 == "c"})print(c)
This new way has several advantages:
- It is faster than implementations with
filter
. - It does away with the need of reversing arrays.
- It removes items in-place, and thus it updates the original array instead of allocating and returning a new array.