问题描述
我有一个自定义类定义如下:
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
。我已经看到一些解决方案,使用 NSMutableArray
和 Equable
但是我不知道如何在这里适应他们;我也知道 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中删除重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!