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)
其中,set 是 Set
类的一个对象。
union() 参数
union()
方法接受一个参数:
- otherSet - 元素的集合。
注意:other
必须是一个有限集合。
union() 返回值
union()
方法返回一个新集合,其中包含 set 和 other(作为参数传递的集合)中的元素。
示例 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()
方法来计算 A 和 B、B 和 C 之间的并集。
示例 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
表示一个从1到4的数字集合,并将其赋值给 total。
最后,我们计算了 total 和 [5,6]
之间的并集。