Andy Andy - 3 months ago 17
Swift Question

How to remove elements from array that match elements in another array

How to remove elements from array that match elements in another array?

Assume we have an array and we loop through it and find out which elements to remove:

var sourceItems = [ ... ]
var removedItems = [SKShapeNode]()

for item : SKShapeNode in sourceItems {
if item.position.y > self.size.height {
removedItems.append(item)
item.removeFromParent()
}
}

sourceItems -= removedItems // well that won't work.

Answer

You can use the filter function.

let a = [1, 2, 3]
let b = [2, 3, 4]

let result = a.filter { element in
    return !b.contains(element)
}

result will be [1]

Or more succinctly...

let result = a.filter { !b.contains($0) }

Check out the Swift Standard Library Reference

Or you can use the Set type.

let c = Set<Int>([1, 2, 3])
let d = Set<Int>([2, 3, 4])
c.subtract(d)