A union is a set that contains values or elements present in the sets we are comparing. We can use the union()
method to get the union between a set and an array.
A set contains unique elements, whereas an array may or may not contain unique elements.
set.union(sequence)
We specify a sequence that could either be an array or a set. The union between the set and this sequence is taken.
It returns a new Set
, which contains the elements of the union of Set
and sequence
.
// create some setslet evenNumbers : Set = [2, 4, 6, 8, 10]let oddNumbers : Set = [3, 5, 7, 9, 11]let alphabets : Set = ["a", "x", "s", "w", "j"]// create some arrayslet numbers = [1, 100, 30, 3]let letters = ["a", "b", "c", "d"]// get and print the uionsprint(evenNumbers.union(numbers).sorted())print(oddNumbers.union(numbers).sorted())print(alphabets.union(letters).sorted())
Set
instances and initialize them.numbers
and letters
.union()
method to get the unions between the sets and arrays and sort the resulting union. Next, we print the results to the console.