Sling Academy
Home/Swift/Swift: 3 Ways to Remove Duplicates from an Array

Swift: 3 Ways to Remove Duplicates from an Array

Last updated: May 03, 2023

Overview

Swift is a powerful, intuitive, and efficient programming language that allows you to write clean, easy-to-read code. Arrays, a fundamental data structure in Swift, are used to store multiple values of the same type.

Duplicate array elements are items in an array that are identical to one or more other items in the array. Depending on the context of your project, duplicate elements can be a hindrance or even a bug, as they can cause incorrect calculations, inaccurate data representation, or inefficient memory usage.

This practical, example-based article will walk you through a couple of different ways to eliminate duplicate elements from a Swift array. Without any other further ado, let’s get started.

Using Set

A Set is a collection type in Swift that stores unique elements in no particular order. By converting an array into a Set and then back into an array, you can quickly get rid of duplicates.

Example:

=let numbers = [1, 2, 3, 1, 3, 5, 6, 2, 5]
let uniqueNumbers = Array(Set(numbers))
print(uniqueNumbers) 
// Output: [1, 5, 2, 3, 6]

Another example (creating an extension):

// declare an extension
extension Array where Element: Hashable {
    func removingDuplicates() -> [Element] {
        return Array(Set(self))
    }
}

let numbers = [1, 2, 3, 4, 4, 5, 6, 6]
let uniqueNumbers = numbers.removingDuplicates()
print(uniqueNumbers)
// Output: [5, 2, 3, 1, 6, 4]

Keep in mind that converting an array to a Set will not maintain the original order of the elements. If you need to preserve the order, see other approaches in this article.

Using the Array.filter() method

Another technique for removing duplicates is to use the filter() method, which allows you to create a new array by filtering the elements of the original array that meet specific criteria. In this case, the criteria would be to include only unique elements.

This method maintains the original order of the elements but may be less efficient than using a Set, as it requires iterating over the entire array.

Example:

let numbers = [1, 2, 3, 1, 3, 5, 6, 2, 5]
var uniqueNumbers: [Int] = []

_ = numbers.filter { item in
    if uniqueNumbers.contains(item) {
        return false
    } else {
        uniqueNumbers.append(item)
        return true
    }
}

print(results)
// Output: [1, 2, 3, 5, 6]

Defining a custom function

You can also create a custom function to remove duplicates from an array. This approach allows for more flexibility and customization, depending on your specific requirements.

Here’s an example of a custom function that removes duplicates while preserving the original order:

func removeDuplicates<T: Equatable>(from array: [T]) -> [T] {
    var uniqueElements: [T] = []
    for item in array {
        if !uniqueElements.contains(item) {
            uniqueElements.append(item)
        }
    }
    return uniqueElements
}

let numbers = [1, 2, 3, 1, 3, 5, 6, 2, 5]
let uniqueNumbers = removeDuplicates(from: numbers)
print(uniqueNumbers) 
// Output: [1, 2, 3, 5, 6]

This custom function uses a generic type to support arrays of any type that conforms to the Equatable protocol.

Conclusion

Removing duplicate elements from an array is a common task in Swift programming. In this tutorial, we’ve explored three methods for eliminating duplicates:

  • Using Set: This method is generally the fastest and requires the least amount of code. However, it does not maintain the original order of the elements.
  • Filter method: This method preserves the original order of the elements but may be slower than using a Set, as it requires iterating over the entire array.
  • Custom function: This method provides the most flexibility and customization but may be less efficient than the other methods. It also requires more code and a deeper understanding of Swift.

Each method has its advantages and disadvantages, so it’s essential to consider your specific requirements when choosing the best approach for your apps.

Next Article: Swift: Ways to Calculate the Product of an Array

Previous Article: Working with Multidimensional Arrays in Swift

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)