In Swift 3 and 4, this will 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 an OP 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 and later there is even a better, faster way that Apple recommended in WWDC2018:
var c = ["a", "b", "c", "d", "e", "f"] c.removeAll(where: {$0 == "c"}) print(c)
This new method has several advantages:
- This is faster than
filter implementations. - This eliminates the need to access arrays.
- It removes elements in place and thus updates the original array, rather than placing and returning a new array.
jvarela Jan 01 '16 at 17:24 2017-01-01 17:24
source share