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
-
What is the basis of the duplicate check? This question is lacking a lot of important details.rmaddy– rmaddy2019年06月01日 17:58:19 +00:00Commented Jun 1, 2019 at 17:58
-
1How about checking for a duplicate before inserting a new item? Or use a set anyway, if possible.vadian– vadian2019年06月01日 17:59:42 +00:00Commented Jun 1, 2019 at 17:59
-
2This has been asked and answered multiple times. Both set-based and order-preserving methods have been provided in the answers.Martin R– Martin R2019年06月01日 18:13:01 +00:00Commented Jun 1, 2019 at 18:13
2 Answers 2
Most efficient way if you don’t care about maintaining the original order in the array
let uniqueUsers = Array(Set(users))
3 Comments
rmaddy
Of course this assumes that
UserModel
properly conforms to Hashable
.gnasher729
A good reason to make it conform :-)
bibscy
I've made it conform to Hashable
Maybe instead of using an array you want to use a set? https://developer.apple.com/documentation/swift/set
1 Comment
Joey Harwood
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.
lang-swift