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.
Here is an Array extension to return the unique list of objects based on a given key:
extension Array {
func unique<T:Hashable>(map: ((Element) -> (T))) -> [Element] {
var set = Set<T>() //the unique list kept in a Set for fast retrieval
var arrayOrdered = [Element]() //keeping the unique list of elements but ordered
for value in self {
if !set.contains(map(value)) {
set.insert(map(value))
arrayOrdered.append(value)
}
}
return arrayOrdered
}
}
for your example do:
let uniqueMessages = messages.unique{$0.id ?? ""}