intersection()
方法返回一个新集合,其中包含两个集合的共同元素。
示例
var A: Set = [2, 3, 5]
var B: Set = [1, 3, 5]
// compute intersection between A and B
print("A n B = ", A.intersection(B))
// Output: A n B = [5, 3]
intersection() 语法
集合 intersection()
方法的语法是
set.intersection(otherSet)
其中,set 是 Set
类的一个对象。
intersection() 参数
intersection()
方法接受单个参数
- otherSet - 元素的集合。
注意:other
必须是一个有限集合。
intersection() 返回值
intersection()
方法返回一个新集合,其中包含 set 和 other(作为参数传递的集合)的共同元素。
示例 1: Swift Set intersection()
var A: Set = ["a", "c", "d"]
var B: Set = ["c", "b", "e" ]
var C: Set = ["b", "c", "d"]
// compute intersection between A and B
print("A n B =", A.intersection(B))
// compute intersection between B and C
print("B n C =", B.intersection(C))
输出
A n B = ["c"] B n C = ["b", "c"]
在这里,我们分别使用 intersection()
方法计算 A 和 B 之间以及 B 和 C 之间的交集。
示例 2: Swift intersection() 和 Ranges 的使用
// create a set that ranges from 1 to 4
var total = Set(1...10)
// compute intersection
print(total.intersection([5,10,15]))
输出
[10, 5]
这里,1...10
表示一个范围从1到10的数字集合,并将其赋值给 total。
最后,我们计算了 total 和 [5,10,15]
之间的交集。
由于只有5和10是共同的,intersection()
方法只打印5和10。