mankee mankee - 1 year ago 100
iOS Question

Removing Duplicates From Array of Custom Objects Swift

I have a custom class defined as follows :

class DisplayMessage : NSObject {
var id : String?
var partner_image : UIImage?
var partner_name : String?
var last_message : String?
var date : NSDate?

Now I have an array
myChats = [DisplayMessage]?
. The
field is unique for each
object. I need to check my array and remove all duplicates from it, essentially ensure that all objects in the array have a unique
. I have seen some solutions using
however I'm not sure how to adapt them here; I also know of
however that doesn't seem to work for an array of custom objects.

Answer Source

You can do it with a set of strings, like this:

var seen = Set<String>()
var unique = [DisplayMessage]
for message in messagesWithDuplicates {
    if !seen.contains(!) {

The idea is to keep a set of all IDs that we've seen so far, go through all items in a loop, and add ones the IDs of which we have not seen.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download