Swift Set intersection()

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)

其中,setSet 类的一个对象。


intersection() 参数

intersection() 方法接受单个参数

  • otherSet - 元素的集合。

注意other 必须是一个有限集合。


intersection() 返回值

  • intersection() 方法返回一个新集合,其中包含 setother(作为参数传递的集合)的共同元素。

示例 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() 方法计算 AB 之间以及 BC 之间的交集。


示例 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 表示一个范围从110的数字集合,并将其赋值给 total

最后,我们计算了 total[5,10,15] 之间的交集。

由于只有510是共同的,intersection() 方法只打印510

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战