Skip to content
DeveloperMemos

Removing Duplicate Elements from an Array in Swift

Swift, Arrays, Algorithms1 min read

Dealing with arrays often involves the need to remove duplicate elements. Swift provides several ways to handle this task, ensuring flexibility depending on whether you need to maintain the order of elements or not.

Using Set for Unordered Unique Elements

If the order of elements is not important, the easiest way to remove duplicates is by converting the array into a Set, which inherently contains unique elements, and then back into an array.

Example:

1let numbers = [1, 4, 2, 2, 2, 3, 6, 3, 24, 22, 15, 2, 60, 15, 6, 15]
2let uniqueNumbers = Array(Set(numbers))
3// [1, 4, 2, 3, 6, 24, 22, 15, 60]

This method is concise but does not preserve the original order of elements.

Preserving Order While Removing Duplicates

To remove duplicates while keeping the original order, you can use a combination of a temporary Set and a filter method.

Example:

1let numbers = [1, 4, 2, 2, 2, 3, 6, 3, 24, 22, 15, 2, 60, 15, 6, 15]
2var seen = Set<Int>()
3let uniqueNumbers = numbers.filter { seen.insert($0).inserted }
4// uniqueNumbers is [1, 4, 2, 3, 6, 24, 22, 15, 60]

In this example, seen.insert($0).inserted returns true for the first occurrence and false for subsequent duplicates.

Conclusion

Removing duplicates from an array in Swift can be achieved efficiently either by using a Set for an unordered list of unique elements or by using a filter method along with a Set to maintain the original order. The choice of method depends on whether the order of elements in the array is significant for your use case.