user1107173 user1107173 - 5 months ago 38
Swift Question

Swift: Up Cast NSManagedObject to subclass Entity

How do I up cast

to subclass entity called
in Swift .

func processEntity(updates: [NSManagedObject]) -> [Relationship] {
let relationship = updates.filter({$ == "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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download