-4

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 ?

S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254
  • http://stackoverflow.com/questions/25738817/does-there-exist-within-swifts-api-an-easy-way-to-remove-duplicate-elements-fro has answers for all Swift versions. – Martin R Mar 21 '17 at 07:55
  • 2
    what have you tried from stackOverflow ? What issues are you facing ? – Umair Afzal Mar 21 '17 at 07:56
  • http://stackoverflow.com/questions/34709066/remove-duplicate-objects-in-an-array – Ahmad F Mar 21 '17 at 07:59

3 Answers3

10

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • How to implements my array as Hashable? – S.M_Emamian Mar 21 '17 at 08:07
  • @S.M_Emamian There are a lot of implementations of `hashcode`. The idea is that each distinct instance has a different hashcode. If two instances have the same hashcode, they are considered "equal". Here is an example: http://stackoverflow.com/a/34705912/5133585 – Sweeper Mar 21 '17 at 08:09
  • @S.M_Emamian: Example in this answer http://stackoverflow.com/a/34709118/1187415 to the "duplicate". – Martin R Mar 21 '17 at 08:10
  • This will not preserve element order of the original array! –  Apr 01 '20 at 07:37
  • @ErikAigner True. Added a note to say that. – Sweeper Apr 01 '20 at 07:39
2

You might want to use Set

// Initialize the Array var sample = [1,2,3,4,5,2,4,1,4,3,6,5]

// Remove duplicates: sample = Array(Set(sample))

print(sample)

Lysdexia
  • 453
  • 8
  • 22
1

If order is not important, you should use a Set instead. Sets only contain unique elements. You can also create a Set from the array, that should eliminate duplicates.

Frank Rupprecht
  • 9,191
  • 31
  • 56