比较和提取2个数组的元素

时间:2019-05-26 11:14:50

标签: arrays swift string

我有2个String数组:

let a = ["jan", "feb", "jun"]

let b = ["jan", "may", "feb"]

我需要检查a数组中的哪些元素不在b数组中,并将结果存储在名为c的数组中。

我尝试使用此扩展名来实现这一点:

extension Array where Element : Hashable {
    func difference(from other: [Element]) -> [Element] {
        let thisSet = Set(self)
        let otherSet = Set(other)
        return Array(thisSet.symmetricDifference(otherSet))
    }
}

但是它给我的结果是两个数组之间的差(即“ may”,“ jun”),而我只需要a数组中不在b数组中的元素。我该如何实现?

2 个答案:

答案 0 :(得分:3)

您要从a中减去 b

return Array(thisSet.subtracting(otherSet))

或者

extension Array where Element : Hashable {
    func difference(from other: [Element]) -> [Element] {
        var temp = self
        temp.removeAll{ other.contains($0) }
        return temp
    }
}

答案 1 :(得分:1)

您需要从a中减去b

return Array(otherSet.subtracting(thisSet))

let a = ["jan", "feb", "jun"]

let b = ["jan", "may", "feb"]

print(b.difference(from: a)) // jun