OneBite.Dev - Coding blog in a bite size

Remove Duplicates From An Array In Swift

Code snippet for how to Remove Duplicates From An Array In Swift with sample and detail explanation

When programming in Swift, often times we come across situations where we need to remove duplicate items from an array. This article offers a step by step guide on how you can do this in an efficient and straightforward manner.

Code snippet to remove duplicates from an array in Swift

In Swift, the primary technique utilized for removing duplicates from an array involves the use of a Set. Here is a simple code snippet to demonstrate:

func removeDuplicates(array: [Int]) -> [Int] {
    let set = Set(array)
    return Array(set)
}

let arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5]
let arrayWithoutDuplicates = removeDuplicates(array: arrayWithDuplicates)
println(arrayWithoutDuplicates)

Code Explanation for removing duplicates from an array in Swift

The above snippet contains the definition of a function named removeDuplicates(). This function takes an array as an input and returns a new array that has no duplicates.

  1. We first declare the function removeDuplicates(), which accepts an array of Integers as a parameter.

  2. Inside the function, we construct a Set from the input array. The aim here is to leverage the property of a Set that doesn’t allow duplicate elements. So when you convert the input array into a Set, any duplicate elements are automatically removed.

  3. Finally, we convert the Set back into an Array and return it. Since the Set does not preserve the ordering of elements, the returned array might not have the same order as the original input array.

In the second part of the code, we call our function removeDuplicates(), passing to it an array arrayWithDuplicates that has some duplicate numbers. The returned array arrayWithoutDuplicates is then printed which shows numbers from original array without any duplicates.

Remember, this technique is quite universal and can be used with arrays of all types, not just integers, making it a versatile tool to have in your Swift programming arsenal.

swift