Find common elements between two arrays in Swift


In this Swift tutorial, you will learn how to get the list of common elements between two arrays. We are going to do something like you can see in the diagram below:

Common elements from two arrays

Without wasting any time, let’s see the code below:

let dressColorsArray = ["red", "green", "purple", "lime", "pink", "blue"]
let shoeColorsArray = ["white", "lime", "black", "yellow", "green"]

// Get common elements from the two arrays
let commonColors = dressColorsArray.filter{ shoeColorsArray.contains($0) }

// or
let commonColors2 = dressColorsArray.filter(shoeColorsArray.contains)

We did it… We have successfully been able to find the common elements between two arrays. You can test the code in the Xcode playground and then print commonColors. The commonColors2 will also give the same output. You can use any one of these.

In the above code, we take two arrays. Then we apply the filter() method for our first array. Inside the filter() method, we use the array contains() method for our second array to check whether elements of the first array exist in the second array.

In a nutshell, we have created a new Swift array with elements available in those two arrays in common.

In the end, we are able to get a new array with the common items from the two arrays we created first.

In our case, the two arrays are dressColorsArray and shoeColorsArray. These two arrays contain some colors as the elements. In this tutorial, we created a new array with the common name of colors from the two arrays we provided.

Alternative method

In the above example, we have used the filter and contains method. But this is not the only way to get the common array elements from two arrays in Swift. We can do it using the Set intersection method.

Below is given the Swift code using the Set to get common elements from our two arrays:

let dressColorsArray = ["red", "green", "purple", "lime", "pink", "blue"]
let shoeColorsArray = ["white", "lime", "black", "yellow", "green"]

let commonColors = Array(Set(dressColorsArray).intersection(Set(shoeColorsArray)))

In the above code, we have converted the arrays into sets and applied the intersection operation. In the end, we again convert the returned set into an array. We did it just in a single line of code.

In this example, the array we will get will be in unordered form, but the elements will be the same as we can see in our first example.