Search code examples
iosarraysswiftduplicatesnsobject

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 id field is unique for each DisplayMessage object. I need to check my array and remove all duplicates from it, essentially ensure that all objects in the array have a unique id. I have seen some solutions using NSMutableArray and Equatable however I'm not sure how to adapt them here; I also know of Array(Set(myChats)) however that doesn't seem to work for an array of custom objects.


Solution

  • 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(message.id!) {
            unique.append(message)
            seen.insert(message.id!)
        }
    }
    

    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.