Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 派生扩展名的类型';s静态函数_Swift_Generics_Swift Extensions - Fatal编程技术网

Swift 派生扩展名的类型';s静态函数

Swift 派生扩展名的类型';s静态函数,swift,generics,swift-extensions,Swift,Generics,Swift Extensions,我想创建一个方法,将特定类的所有NSManagedObject作为扩展返回: extension NSManagedObject { static func getAll() -> [NSManagedObject]? { // code } } 如何指定返回对象的确切类型?因此,对于类Animal,我可以在下一个示例中推断类型: let animals = Animal.getAll() // I want to animals already be [Ani

我想创建一个方法,将特定类的所有NSManagedObject作为扩展返回:

extension NSManagedObject {
   static func getAll() -> [NSManagedObject]? {
       // code
   }
}
如何指定返回对象的确切类型?因此,对于类Animal,我可以在下一个示例中推断类型:

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

是否要以相同的方式获取所有对象?如果是这样,您可以尝试以下方法:

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