且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

快速检查一个数组是否包含另一个数组的元素

更新时间:2022-11-01 18:54:14

您可以简单地从第一个集合中创建一个集合,并使其与另一个集合相交:

You can simply create a set from your first collection and get its intersection with the other collection:

let array1 = ["user1", "user2", "user3", "user4"]
let array2 = ["user3", "user5", "user7", "user9", "user4"]
let intersection = Array(Set(array1).intersection(array2)) // ["user4", "user3"] 


请注意,结果集合的顺序是不可预测的.如果您想保留第一个集合的顺序,则可以创建第二个集合的集合并过滤无法插入其中的元素:


Note that the order of the resulting collection is unpredictable. If you would like to preserve the order of the first collection you can create a set of the second collection and filter the elements that cannot be inserted to it:

var set = Set(array2)
let intersection = array1.filter { !set.insert($0).inserted }  // ["user3", "user4"]


您还可以在RangeReplaceableCollection上创建自己的交集方法:


You can also create your own intersection method on RangeReplaceableCollection:

extension RangeReplaceableCollection {
    func intersection<S: Sequence>(_ sequence: S) -> Self where S.Element == Element, Element: Hashable {
        var set = Set(sequence)
        return filter { !set.insert($0).inserted }
    }
}


用法:


Usage:

let intersection = array1.intersection(array2)  // ["user3", "user4"]