0

I have an array of custom objects, a.k.a users, and some of them are duplicates.

How can I make sure there is only one of each element? No duplicates.
Also, what's the most efficient way?

var users: UserModel = [UserModel]()
rmaddy
319k44 gold badges548 silver badges590 bronze badges
asked Jun 1, 2019 at 17:44
3
  • What is the basis of the duplicate check? This question is lacking a lot of important details. Commented Jun 1, 2019 at 17:58
  • 1
    How about checking for a duplicate before inserting a new item? Or use a set anyway, if possible. Commented Jun 1, 2019 at 17:59
  • 2
    This has been asked and answered multiple times. Both set-based and order-preserving methods have been provided in the answers. Commented Jun 1, 2019 at 18:13

2 Answers 2

2

Most efficient way if you don’t care about maintaining the original order in the array

let uniqueUsers = Array(Set(users))

3 Comments

Of course this assumes that UserModel properly conforms to Hashable.
A good reason to make it conform :-)
I've made it conform to Hashable
0

Maybe instead of using an array you want to use a set? https://developer.apple.com/documentation/swift/set

answered Jun 1, 2019 at 17:52

1 Comment

This could be a good answer if you stated it an answer rather than another question. Additionally you should provide the essential parts of the link in your answer in case the link breaks or changes in the future.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.