An intersection between a set and an array in Swift is the set of values present in both instances. It is worth remembering that a set is a group of unique elements, and an array is also a group of elements but must not necessarily be unique. We can check for the intersection between a set and an array using the intersection()
method.
set.intersection(array)
array
: This is an array of elements.
The value returned is a new set of elements common to both the set instance, set
and the array, array
.
// create some setslet evenNumbers : Set = [2, 4, 6, 8, 10]let oddNumbers : Set = [3, 5, 7, 9, 11]// create an arraylet randomNumbers = [1, 4, 7, 9, 10, 12]// create an intersectionprint(evenNumbers.intersection(randomNumbers))print(oddNumbers.intersection(randomNumbers))
intersection()
method to get the intersection between the sets and the array. The results are printed to the console.