-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 ?

3

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

How to implements my array as Hashable?
@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: stackoverflow.com/a/34705912/5133585
@S.M_Emamian: Example in this answer stackoverflow.com/a/34709118/1187415 to the "duplicate".
This will not preserve element order of the original array!
@ErikAigner True. Added a note to say that.
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)

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.