I have two arrays of two different objects
object 1:
Class partner {
var pImage: String?
var pTimeStamp: NSDate?
var pTitle: String?
var ID: String?
}
object 2:
Class customer {
var cImage: String?
var cTimeStamp: NSDate?
var cTitle: String?
var ID: String?
var isCustomer : Bool?
}
I want to create an array
(in a efficient way, of-course) out of these two array
objects
such that no partner and customer object with same ID (cID,pID) should repeat within new Array
.
Basically union of these two array based on IDs. Please do help.
EDIT: these objects are stored in CoreData and at the time I do want above desired result I have already two array of these object
The super-clever way would be to make Set do all the work for you. Make these objects adopt a common protocol with an ID property. Define equality for that protocol to mean having the same ID value. Now, if you don't care about order, coerce the arrays to Sets and union the sets. If you do care about order, you'll have to use NSOrderedSet instead. You can coerce back to Array after performing the union operation.
The alternative (the "dumb" way) is to cycle thru the arrays, building a dictionary whose key is the ID value. Like the set based on ID equality, this prevents the repetition you're trying to avoid. It's not inefficient because you're only cycling once thru each array, and lookup of the dictionary key is fast. When you've built the dictionary, convert back to an array. Again, however, you're going to lose the original array order unless you take additional measures.
(Both these answers, however, assume that you're willing to modify your objects so that they can even live in a common collection; as things stand, they can't, as they are two unrelated types.)