Remove duplicate elements from a Swift array


There are multiple possible ways to remove duplicate elements from an array in Swift programming. Below is given an example that is one of the easiest ways with the Set:


let myArray = [1,2,3,2,4,4,5]

let arrayWithUnique = Array(Set(myArray))

print("Original array: \(myArray)")
print("Array with unique elements: \(arrayWithUnique)")

Output:

Original array: [1, 2, 3, 2, 4, 4, 5]
Array with unique elements: [2, 5, 1, 3, 4]

Note: The elements of the unique array may not be in the same order, it will reorder the elements.

In the above example, we have used the Swift Set() method to remove the duplicate items from the array.

If you read our tutorial on Sets in Swift, you already know that a set always contains unique elements, no matter how many times an item will be there, it will take only once. Thus any duplicate elements will be erased which makes a set always consist of unique elements.

Using the Array() method will again back the set to an array with the elements that are unique.

But one thing you should keep in mind is that the elements may not be in the same order. Every time you run the program will reorder the position of the elements of the array.

As the previous code reorder the elements of our Swift array during removing the duplicate items, so now I am going to let you know another way to perform this task that will keep the same order as the original array.

Remove duplicate elements keeping the same order for the elements

Below is an extension on an array for removing duplicate elements while keeping the item order maintained:

extension Array where Element: Hashable {
    func uniqueArrItems() -> [Element] {
        var dictAdded = [Element: Bool]()

        return filter {
            dictAdded.updateValue(true, forKey: $0) == nil
        }
    }

    mutating func removeDuplicates() {
        self = self.uniqueArrItems()
    }
}


let myNums = [1,2,2,3,4,4,5,6,5]
let uniqueArray = myNums.uniqueArrItems()


print(uniqueArray)

The output of the above program:

[1, 2, 3, 4, 5, 6]

As you can see, we are able to extract unique elements from our Swift array keeping the same order of the elements.

In our code, we have two methods. One is the uniqueArrItems() and the other one is removeDuplicates().

uniqueArrItems() returns array by removing duplicates and removeDuplicates() plays the role of changing the array in place with the new unique array.

In the uniqueArrItems() function, we are using filter() and a dictionary. When you call updateValue() on a dictionary it returns nil if the key is new. In this way, we can figure out which items are unique.

In the end, as a result, we were able to get a new Swift array with unique elements.