导出扩展名静态函数的类型

时间:2017-04-29 10:26:04

标签: swift generics swift-extensions

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

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

如何指定返回对象的确切类型?因此,对于Animal类,我可以在下一个示例中推断类型:

SELECT *, (`expire_date` IS NULL) AS `permanent` 
FROM `player_bans` 
WHERE (`ip` = '%e' OR `userid` = '%d') AND 
    (`expire_date` > NOW() OR `expire_date` IS NULL) 
LIMIT 1

1 个答案:

答案 0 :(得分:1)

你打算以同样的方式获取所有对象吗?如果是这样,你可以这样试试:

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