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

编程入门 行业动态 更新时间:2024-10-11 23:25:04
本文介绍了快速检查一个数组是否包含另一个数组的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

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

本文发布于:2023-11-29 14:06:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646605.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   快速

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!