如何从数组中删除与另一个数组中的元素匹配的元素

时间:2014-08-11 19:23:38

标签: arrays swift

如何从数组中删除与另一个数组中的元素匹配的元素?

假设我们有一个数组,我们遍历它并找出要删除的元素:

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.

2 个答案:

答案 0 :(得分:9)

您可以使用filter功能。

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

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

result将为[1]

或者更简洁......

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

查看Swift Standard Library Reference

或者您可以使用Set类型。

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

答案 1 :(得分:0)

请注意,如果使用Set选项,结果只是唯一值,并且不会保持初始排序,如果这对您很重要,而Array过滤器选项将保持初始数组的顺序,至少保留哪些元素。

Swift 3

let c = Set<Int>([65, 1, 2, 3, 1, 3, 4, 3, 2, 55, 43])
let d = Set<Int>([2, 3, 4])
c.subtracting(d)

c = {65, 2, 55, 4, 43, 3, 1}
d = {2, 3, 4}
result = {65, 55, 43, 1}