Search code examples
iosswiftxcodeswift3

How to remove duplicate elements inside an array - swift 3


I want to remove duplicate elements from an array. there are many answers in stack overflow but for swift 3.

my array:

var images = [InputSource]()
... // append to array

how to remove duplicate elements from this array?

Is there any native api from swift 3 ?


Solution

  • Make sure that InputSource implements Hashable, otherwise Swift can't know which elements are equal and which are not.

    You just do this:

    let withoutDuplicates = Array(Set(images))
    

    Explanation:

    images is turned into a set first. This removes all the duplicates because sets can only contain distinct elements. Then we convert the set back to an array.

    According to this answer, this is probably optimized by the compiler.

    The disadvantage of this is that it might not preserve the order of the original array.