在Swift数组上设置操作(联合,交集)? [英] Set operations (union, intersection) on Swift array?

查看:179
本文介绍了在Swift数组上设置操作(联合,交集)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何标准库调用可用于对两个数组执行集合操作,或者自己实现此类逻辑(理想情况下尽可能在功能上和效率上尽可能)?

Are there any standard library calls I can use to either perform set operations on two arrays, or implement such logic myself (ideally as functionally and also efficiently as possible)?

推荐答案

是的,Swift有 Set 类。

Yes, Swift has the Set class.

let array1 = ["a", "b", "c"]
let array2 = ["a", "b", "d"]

let set1:Set<String> = Set(array1)
let set2:Set<String> = Set(array2)

Swift 3.0+可以对集合执行操作:

Swift 3.0+ can do operations on sets as:

firstSet.union(secondSet)// Union of two sets
firstSet.intersection(secondSet)// Intersection of two sets
firstSet.symmetricDifference(secondSet)// exclusiveOr

Swift 2.0可以计算数组参数:

Swift 2.0 can calculate on array arguments:

set1.union(array2)       // {"a", "b", "c", "d"} 
set1.intersect(array2)   // {"a", "b"}
set1.subtract(array2)    // {"c"}
set1.exclusiveOr(array2) // {"c", "d"}

Swift 1.2+可以在集合上计算:

Swift 1.2+ can calculate on sets:

set1.union(set2)        // {"a", "b", "c", "d"}
set1.intersect(set2)    // {"a", "b"}
set1.subtract(set2)     // {"c"}
set1.exclusiveOr(set2)  // {"c", "d"}

如果您使用自定义结构,则需要实现Hashable。

If you're using custom structs, you need to implement Hashable.

感谢Michael Stern在Swift 2.0更新中的评论。

Thanks to Michael Stern in the comments for the Swift 2.0 update.

感谢Amjad Husseini的评论为Hashable信息。

Thanks to Amjad Husseini in the comments for the Hashable info.

这篇关于在Swift数组上设置操作(联合,交集)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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