Search code examples
swiftgenericsswift-extensions

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]?

Solution

  • 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()