在 Swift 数组上设置操作(联合、交集)? [英] Set operations (union, intersection) on Swift array?
问题描述
是否有任何标准库调用可用于对两个数组执行设置操作,或自己实现此类逻辑(理想情况下,功能和效率尽可能高)?
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屋!