user1107173 user1107173 - 20 days ago 8
Swift Question

Swift: Up Cast NSManagedObject to subclass Entity

How do I up cast

NSManagedObject
to subclass entity called
Relationship
in Swift .

func processEntity(updates: [NSManagedObject]) -> [Relationship] {
let relationship = updates.filter({$0.entity.name == "Relationship"}
// here how do I return an array of [Relationship]
}

Answer Source

Don't compare names, just do a normal cast.

func processEntity(updates: [NSManagedObject]) -> [Relationship] {
    return updates.flatMap({ $0 as? Relationship })
}

If you're unfamiliar with it, flatMap is basically a filter plus a map. If the block returns nil, the element is omitted from the resulting array, otherwise the array will contain the value returned by the block. So in this case we're looking at every NSManagedObject and saying "are you really a Relationship?", and we keep the values that are Relationships.