Remove Duplicate elements from an array in Swift with an example

This tutorial explains different ways to remove duplicate elements from an array with code examples

  • Convert Array to Set using Set(array), again convert to Array using Array(Set)
  • Iterate an array and add an element to a set, convert to the array.

For example, the Input array contains the following elements.

array=[1,11,1,2,3,1,3]

1 and 3 are repeated and removed from an array, the following is an array. Output:

array=[1,11,2,3]

How to remove duplicate elements from an array in Swift with examples

There are multiple ways we can remove duplicate elements.

  • Use a Set data structure Set is a data structure used to store unique elements.

Here are the following steps required

  • First, Convert array into Set using the constructor
  • Next, convert set to Array using the array constructor

Here is an example

var numbers=[1,11,1,2,3,1,3]
let uniqueUnordered = Array(Set(numbers))

puts (uniqueUnordered)

Output:

[1,11,2,3]

Arrays contain order items, this approach, Set does not follow the order.

  • Using an array for in loop It is an example of the iteration of elements and adding into Set type.
var numbers=[1,11,1,2,3,1,3]
var result = Set<Int>()
for i in numbers {
result.insert(i)
}
print(result)