我有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
数组中的元素。我该如何实现?
答案 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