Casey Monta
Casey Monta

Reputation: 13

Derive type for extension's static func

I want to make a method to return all NSManagedObject of a specific class as an extension:

extension NSManagedObject {
   static func getAll() -> [NSManagedObject]? {
       // code
   }
}

How can I specify the exact type of returned objects? So, for class Animal, I could infer type in the next example:

let animals = Animal.getAll() // I want to animals already be [Animal]?, not [NSManagedObject]?

Upvotes: 1

Views: 209

Answers (1)

iWheelBuy
iWheelBuy

Reputation: 5679

Are you going to fetch all objects the same way? If so, you can try this way:

import UIKit
import CoreData

protocol AllGettable {
    associatedtype GetObjectType
    static func getAll() -> [GetObjectType]?
}

extension AllGettable {
    static func getAll() -> [Self]? {
        return []/* fetch your objects */ as? [Self]
    }
}

class Animal: NSManagedObject, AllGettable {}

let animals = Animal.getAll()

Upvotes: 1

Related Questions