How to get the union of a set and an array in Swift

Overview

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.

Differences between a set and an array

A set contains unique elements, whereas an array may or may not contain unique elements.

Syntax

set.union(sequence)
Get the union between a set and an array in Swift

Parameter

We specify a sequence that could either be an array or a set. The union between the set and this sequence is taken.

Return value

It returns a new Set, which contains the elements of the union of Set and sequence.

Example

// create some sets
let 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 arrays
let numbers = [1, 100, 30, 3]
let letters = ["a", "b", "c", "d"]
// get and print the uions
print(evenNumbers.union(numbers).sorted())
print(oddNumbers.union(numbers).sorted())
print(alphabets.union(letters).sorted())

Explanation

  • Lines 3–5: We declare three Set instances and initialize them.

  • Line 8–9: We declare two arrays, numbers and letters.

  • Lines 12–14: We use the union() method to get the unions between the sets and arrays and sort the resulting union. Next, we print the results to the console.

Free Resources