为什么我需要转换此通用返回值?

时间:2018-01-17 17:33:55

标签: swift syntax

我对这里的仿制药感到困惑。 static关键字让我很难理解。

import CoreData

@objc(Performer)
public class Performer: NSManagedObject, Fetchable {

  @NSManaged public var dob: Date

  @NSManaged public var firstName: String

  @NSManaged public var lastName: String
}

protocol Fetchable {
  static func fetchAll<T: NSManagedObject>(withPredicate predicate: NSPredicate?, in context: NSManagedObjectContext) throws -> [T]
}

extension Fetchable {

  static func fetchAll<T: NSManagedObject>(withPredicate predicate: NSPredicate?, in context: NSManagedObjectContext) throws -> [T] {
    let entityName = String(describing: self)
    let request = NSFetchRequest<T>(entityName: entityName)
    request.predicate = predicate
    return try context.fetch(request)
  }
}

let performers: [NSManagedObject] = try! Performer.fetchAll(in: context)

//或

let performers: [Performer] = try! Performer.fetchAll(in: context) as! [Performer]

//或

编辑:这一行是我的问题的焦点,因为它抛出了一个错误。但是通过杀死Xcode并重新启动来修复它。

let performers: [Performer] = try! Performer.fetchAll(in: context)

1 个答案:

答案 0 :(得分:0)

编译器无法推断fetchAll<T: NSManagedObject>的泛型类型,因为此类型没有传递参数。这就是为什么必须注释(不是强制转换)类型的原因。

要返回正确的NSManagedObject子类,请使用associatedtype例如

protocol Fetchable {
    associatedtype FetchableType: NSManagedObject = Self
    static var entityName : String { get }
    static func fetchAll(withPredicate predicate: NSPredicate? = nil, in context: NSManagedObjectContext) throws -> [FetchableType]
}

extension Fetchable where FetchableType == Self {

    static var entityName : String {
        return NSStringFromClass(self).components(separatedBy: ".").last!
    }

    static func fetchAll(withPredicate predicate: NSPredicate? = nil, in context: NSManagedObjectContext) throws -> [FetchableType] {
        let request = NSFetchRequestFetchableType>(entityName: entityName)
        request.predicate = predicate
        return try context.fetch(request)
  }
}

现在此行返回[Performer]而没有类型转换

let performers = try! Performer.fetchAll(in: context)