快速检查一个数组是否包含另一个数组的元素 [英] Check if an array contains elements of another array in swift

查看:144
本文介绍了快速检查一个数组是否包含另一个数组的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个数组是否至少包含另一个数组的一个或多个元素,并迅速将它们打印出来.这是我的情况:

I need to check if an array contains at least one or more elements of another array and print them out in swift. This is my situation:

var array1 = ["user1", "user2", "user3", "user4"]
var array2 = ["user3, "user5", "user7", "user9, "user4"]

//I need to get back an array that says that both the arrays contains ex. "user3" and "user4"

我在网上搜索,但只找到了相反的答案,该问题有助于使用 array.symmetricDifference()

I searched the web but i only found the opposite answer that helps t check if there is a difference between 2 arrays using array.symmetricDifference()

有什么帮助吗???谢谢

Any helps??? Thanks

推荐答案

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

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"]

这篇关于快速检查一个数组是否包含另一个数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆