OneBite.Dev - Coding blog in a bite size

Find The Common Elements In Two Arrays In Swift

Code snippet for how to Find The Common Elements In Two Arrays In Swift with sample and detail explanation

Dealing with arrays is a regular part of working with Swift. An interesting challenge that can often arise is finding the common elements in two different arrays. This article will discuss a simple and effective solution to this problem in Swift.

Code Snippet: Finding Common Elements In Two Arrays

Firstly, let’s start with a simple straightforward Swift code snippet that would find the common elements in two arrays.

let array1 = [1, 2, 3, 4, 5]
let array2 = [4, 5, 6, 7, 8]
let commonElements = Array(Set(array1).intersection(Set(array2)))
print(commonElements)

In the above code snippet, array1 and array2 are arrays that we want to find the common elements from. commonElements is an array that will hold these common elements. The print function then prints these common elements to the console.

Code Explanation: Finding Common Elements In Two Arrays

Step-by-step, here’s how this code works:

  1. let array1 = [1, 2, 3, 4, 5] and let array2 = [4, 5, 6, 7, 8]: These two lines define the two arrays that we want to check for common elements.

  2. let commonElements = Array(Set(array1).intersection(Set(array2))): This is where the magic happens. Let’s break it down:

    a. Set(array1).intersection(Set(array2)): This line turns array1 and array2 into Set objects, and then comparison using intersection is performed to find the common elements. In Swift, intersection performs a “set intersection” operation, which essentially means “find the elements that this set and another set have in common.”

    b. Array(Set(...)): Then, we convert the Set back into an Array. This is because we started with Arrays, and the desired final output is also an Array.

  3. print(commonElements): This line prints the array of common elements to the console so we can confirm that our code is working as expected.

The beauty of this particular piece of Swift code is that it’s both clear and efficient. It gives a clear insight into what you’re trying to achieve, and it typically runs quickly, even for larger arrays. This makes it a nice choice whenever you need to find the common elements within two arrays in Swift.

swift