Swift Array: removing duplicate elements.

Stefano Frosoni
If let swift = Programming!
2 min readMar 7, 2017

Recently I had to remove duplicate items from an Swift Array while maintaining the original order.

Searching on the web you can find many solutions but most of them retun a copy of the Array. According to Apple’s Swift guide:

If you create an array, a set, or a dictionary, and assign it to a variable, the collection that is created will be mutable. This means that you can change (or mutate) the collection after it is created by adding, removing, or changing items in the collection.

I didn’t want to create any sort of copy of the Array being not forced to use an immutable array. If we declare the array as a variable we can use the Mutating Keyword so we can directly remove duplicate elements from the Array.

So my prefered solutions was just the simplest one using an Array Extension.

Update On 09/2023:

After revisiting this article and receiving some feedback I figured out that there is a more efficient approach to the problem.

The original code had a complexity of O(N²) because it iterated through each element in the array once, taking O(n) time. Additionally inside the loop, I used the contains method, which, in the worst case, can also take O(n) time to check for the presence of an element.

The updated version below is more efficient, with a time complexity of O(n). It provides both a function to generate a new array with duplicates removed and a mutating function that returns a new array without modifying the original one.

extension Array where Element: Hashable {
//Returns a new array without duplicates,
func removingDuplicates() -> [Element] {
var addedDict = Set<Element>()
return filter {
addedDict.insert($0).inserted
}
}
//Modifies the array in-place to remove duplicates
mutating func removeDuplicates() {
self = self.removingDuplicates()
}
}

Some examples below:

    var numbers = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6]
numbers.removeDuplicates()
print(numbers) // Output: [1, 2, 3, 4, 5, 6]

var words = ["apple", "banana", "apple", "orange", "banana"]
let uniqueWords = words.removingDuplicates()
print(uniqueWords) // Output: ["apple", "banana", "orange"]

Thanks for all the feedback!

I hope you find this article useful. Thanks for reading!

Follow me on Twitter

--

--