Related Tags

swift
communitycreator

# How to find the intersection between a set and an array in Swift

Theodore Kelechukwu Onyejiaku

### 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 sets
let evenNumbers : Set = [2, 4, 6, 8, 10]
let oddNumbers : Set = [3, 5, 7, 9, 11]

// create an array
let randomNumbers = [1, 4, 7, 9, 10, 12]

// create an intersection
print(evenNumbers.intersection(randomNumbers))
print(oddNumbers.intersection(randomNumbers))
Get the intersection between a set and an array in Swift

### 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.

RELATED TAGS

swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time