DJSK DJSK - 1 year ago 53
Swift Question

Filter array of Core Data objects with another array of objects with matching property

I have a Core Data object class for images:

@objc class Image: NSManagedObject {
@NSManaged var imageData: NSData?
@NSManaged var recordID: NSNumber?
@NSManaged var updatedAt: NSDate?

I have two different arrays which will contain these objects:

var container0 = [Image]()
var container1 = [Image]()

What I want to do is write a function that will filter out any Image objects in container1 where the recordID matches the recordID of any object in container2.

Something like:

func returnIntersectionByRecordID() -> [Image] {

var intersection = [Image]()

for object0 in container0 {
for object1 in container1 {
if object0.recordID == object1.recordID {
return intersection

However, I'd like to do this with a filter instead.

Answer Source

I come into two steps. First, get the ids of second array (container2) using map

// the will produce array if ids
let ids ={ return $0.recordId }) 

Then, do filtering

let result = container.filter({ ids.contains($0.recordId) })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download