gpt4 book ai didi

swift - 为什么我需要转换这个通用返回值?

转载 作者:行者123 更新时间:2023-11-30 11:51:05 27 4
gpt4 key购买 nike

我对这里的泛型感到困惑。 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)

最佳答案

编译器无法推断 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 = NSFetchRequest<FetchableType>(entityName: entityName)
request.predicate = predicate
return try context.fetch(request)
}
}

现在这一行返回 [Performer]没有类型转换

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

关于swift - 为什么我需要转换这个通用返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306874/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com