How to find the intersection between a set and an array in Swift
Overview
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.
Syntax
set.intersection(array)
Get the intersection between a Set and an Array in Swift
Parameters
array : This is an array of elements.
Return value
The value returned is a new set of elements common to both the set instance, set and the array, array.
Example
// 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))
Explanation
- Line 2 and 3: We create two sets.
- Line 6: We create an array.
- Line 9 and 10: We use the
intersection()method to get the intersection between the sets and the array. The results are printed to the console.