Swift Set union()

union() 方法返回一个包含所有集合中不重复元素的新集合。

示例

var A: Set = [2, 3, 5]
var B: Set = [1, 3, 5]

// compute union between A and B print("A U B = ", A.union(B))
// Output: A U B = [1, 2, 3, 5]

union() 语法

set union() 方法的语法是:

set.union(otherSet)

其中,setSet 类的一个对象。


union() 参数

union() 方法接受一个参数:

  • otherSet - 元素的集合。

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


union() 返回值

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

示例 1:Swift set union()

var A: Set = ["a", "c", "d"]
var B: Set = ["c", "d", "e" ]
var C: Set = ["b", "c", "d"]

// compute union between A and B print("A U B =", A.union(B))
// compute union between B and C print("B U C =", B.union(C))

输出

A U B = ["d", "e", "a", "c"]
B U C = ["d", "e", "b", "c"]

在这里,我们分别使用了 union() 方法来计算 ABBC 之间的并集。


示例 2:Swift union() 和 Range 的使用

// create a set that ranges from 1 to 4
var total = Set(1...4)

// compute union print(total.union([5,6]))

输出

[6, 3, 2, 5, 1, 4]

在这里,1...4 表示一个从14的数字集合,并将其赋值给 total

最后,我们计算了 total[5,6] 之间的并集。

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

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

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

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