我该如何执行以下代码?

    func setupFetchResultController<AnyNSManagedObject>(entityToFetch: AnyNSManagedObject) {
    let fetchRequest:NSFetchRequest<entityToFetch> = entityToFetch.fetchRequest()
}

它会产生错误消息:
使用未声明的类型“entityToFetch”
当我尝试了下面的代码
    func setupFetchResultController<AnyNSManagedObject>(entityToFetch: AnyNSManagedObject) {
    let fetchRequest:NSFetchRequest<AnyNSManagedObject> = AnyNSManagedObject.fetchRequest()
}

它还生成了错误消息:
类型“AnyNSManagedObject”不符合协议“NSFetchRequestResult”

最佳答案

使用泛型

func setupFetchResultController<T: NSManagedObject>(entityToFetch: T) {
    let fetchRequest = T.fetchRequest()
}


func setupFetchResultController<T: NSManagedObject>(entityToFetch: T) {
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = T.fetchRequest()
}

关于swift - 如何在Swift中将类类型作为函数参数传递?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56862715/

10-11 04:35