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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With