Swift – Find Union of Sets

To find union of Sets in Swift, call union() method on this Set and pass the other set as argument to it. Set.union() returns a new Set with the elements of the two Sets.

Examples

In the following example, we take two Sets: set1 and set2, and find union of these two Sets using union() method.

main.swift

</>
Copy
let set1: Set = [2, 4, 6, 8]
let set2: Set = [2, 8, 14, 22]

let result = set1.union(set2)

print("Set 1 : \(set1)")
print("Set 2 : \(set2)")
print("Union : \(result)")

Output

Set 1 : [2, 6, 4, 8]
Set 2 : [22, 2, 14, 8]
Union : [2, 6, 22, 4, 14, 8]
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we learned how to find union of two Sets using Set.union() method.