Swift Essentials - Remove Duplicates
Swift Array contains a lot of quality of life functions that help the developer code operations on Array elements. One thing that the Swift Standard Library falls short is in it’s ability to remove duplicates from an Array.
By leveraging Swift Extensions we can create a function that enhances the Swift Array built-in functionality to remove duplicates, provided their element conforms to the Equatable protocol.
We begin by writing a Swift Array Extension, specifying that it should only apply if the Element conforms to Equatable. Example of native conformed Equatable Types are for example String and scalar values like Int, Double, etc.
extension Array where Element: Equatable {
}
We then create the removingDuplicates
function that creates a new Array, by filtering duplicate values. The ideia is to loop the original Array, adding the elements to a temporary array addedDict
. If a subsequent element in the loop is already added to the temporary array, we return false in the filter function so that is removed from the final returned Array.
func removingDuplicates() -> [Element] {
var addedDict = [Element]()
return filter {
if addedDict.contains($0) {
return false
}
addedDict.append($0)
return true
}
}
The function above creates a new Array, but in some cases we might want to mutate the current Array by removing the duplicates. In this case we can create a new mutating function like so:
mutating func removeDuplicates() {
self = self.removingDuplicates()
}
Examples
Example 1 - removingDuplicates
let array = [1, 2, 2, 3, 3, 4, 4];
let uniqueArray = array.removingDuplicates();
// print(array) -> [1, 2, 2, 3, 3, 4, 4]
// print(uniqueArray) -> [1, 2, 3, 4]
Example 2 - removeDuplicates
var array = [1, 2, 2, 3, 3, 4, 4];
array.removeDuplicates();
// print(array) -> [1, 2, 3, 4]
Note that on Example 2, array must be a variable because the function is mutating, as in Example 1 variables can be constants.
Complete Extension
The complete extension code can be seen below.