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
  • 314,917
  • 42
  • 532
  • 579
bibscy
  • 2,598
  • 4
  • 34
  • 82
  • What is the basis of the duplicate check? This question is lacking a lot of important details. – rmaddy Jun 01 '19 at 17:58
  • 1
    How about checking for a duplicate **before** inserting a new item? Or use a set anyway, if possible. – vadian Jun 01 '19 at 17:59
  • 2
    This has been [asked and answered multiple times](https://stackoverflow.com/search?q=%5Bswift%5D+array+remove+duplicates). Both set-based and order-preserving methods have been provided in the answers. – Martin R Jun 01 '19 at 18:13

2 Answers2

2

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

let uniqueUsers = Array(Set(users))
Alexander C
  • 676
  • 1
  • 5
  • 12
0

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

Jesus
  • 36
  • 1
  • 6
  • 2
    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. – Joey Harwood Jun 01 '19 at 18:00