 # Swift Set union()

In this tutorial, we will learn about the Swift Set union() method with the help of examples.

The `union()` method returns a new set with distinct elements from all the sets.

### Example

``````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() 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()

``````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))``````

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

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

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

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]`.