The union() method returns a new set with distinct elements from all the sets.
Example
union() Syntax
The syntax of the set union() method is:
set.union(otherSet)
Here, set is an object of the Set class.
union() Parameters
The union() method takes a single parameter:
- otherSet - The set of elements.
Note: The other must be a finite set.
union() Return Value
- The
union()method returns a new set with elements from the set and other (set passed as an argument).
Example 1: Swift set union()
Output
A U B = ["d", "e", "a", "c"] B U C = ["d", "e", "b", "c"]
Here, we have used the union() method to compute the union between A and B & B and C respectively.
Example 2: Use of Swift union() and Ranges
Output
[6, 3, 2, 5, 1, 4]
Here, 1...4 represents a set of numbers that ranges from 1 to 4 and is assigned to total.
Finally, we have computed the union between total and [5,6].