OneBite.Dev - Coding blog in a bite size

Find The Unique Elements In Two Arrays In Swift

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

In this article, we will delve into an interesting task that is commonly required when working with arrays in Swift—finding the unique elements in two arrays. By the end of this read, not only will you have a grasp of how to do it, but you will also understand the underlying workings.

Code snippet for Finding the Unique Elements in Two Arrays

Here is a Swift code snippet that demonstrates how to achieve this:

func uniqueElements<T: Hashable>(from array1: [T], and array2: [T]) -> [T] {
    let allElements = array1 + array2
    let uniqueElements = Array(Set(allElements))
    return uniqueElements
}

// Let's test the function
let array1 = [1, 2, 3, 4, 5]
let array2 = [4, 5, 6, 7, 8]
let unique = uniqueElements(from: array1, and: array2)
print(unique)   // prints: [2, 3, 4, 5, 6, 7, 8, 1]

Code Explanation for Finding the Unique Elements in Two Arrays

Starting with the function declaration, we define the uniqueElements() function that takes two arrays as parameters and returns an array. Note that function operates on arrays of any type that conforms to Hashable protocol. This means you can pass arrays of not just integers or floating point values but also of custom types.

Moving on to the function body, we start by concatenating array1 and array2. This creates a larger array encompassing all the elements from the two input arrays. However, this array may contain duplicate elements.

To find the unique elements, we utilise Set in Swift. A set is a collection where all elements must be unique. Thus, by initializing a set using our array, any duplicates are automatically removed. The downside of a set is that it does not maintain element ordering.

Next, we transform the set back into an array. This step is necessary because our function is supposed to return an array, and arrays are often more practical to work with than sets due to their ordered nature and a wide range of built-in functions.

Finally, the function returns this array of unique elements.

The last part of the code snippet is simply a test of our function. We initialize two integer arrays, array1 and array2, with some overlapping elements. We then pass these arrays to our function and print the result. The output array only contains unique elements, showcasing that our function works as desired.

swift