Swift 从自定义对象数组中删除重复项 [英] Removing Duplicates From Array of Custom Objects Swift

查看:45
本文介绍了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?
}

现在我有一个数组 myChats = [DisplayMessage]?.id 字段对于每个 DisplayMessage 对象都是唯一的.我需要检查我的数组并从中删除所有重复项,基本上确保数组中的所有对象都具有唯一的 id.我已经看到了一些使用 NSMutableArrayEquatable 的解决方案,但是我不确定如何在这里调整它们;我也知道 Array(Set(myChats)) 但这似乎不适用于自定义对象数组.

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.

推荐答案

你可以用一组字符串来做,像这样:

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!)
    }
}

我们的想法是保留一组到目前为止我们见过的所有 ID,循环遍历所有项目,并添加我们没有见过的 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.

这篇关于Swift 从自定义对象数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆