Removing Duplicates From Array of Custom Objects Swift

后端 未结 4 1438
孤独总比滥情好
孤独总比滥情好 2020-11-30 08:04

I have a custom class defined as follows :

class DisplayMessage : NSObject {
var id : String?
var partner_image : UIImage?
var partner_name : String?
var la         


        
4条回答
  •  星月不相逢
    2020-11-30 08:21

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

    var seen = Set()
    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.

提交回复
热议问题