[英]Error casting NSFetchRequest<T> to NSFetchRequest<NSFetchRequestResult> where T is generic NSManagedObject
I want to state that I am fairly new to Swift and I was exploring CoreData concepts.我想 state 我对 Swift 还很陌生,我正在探索 CoreData 概念。 I tried to test with a ToDo list app which on welcome screen shows user created task categories and upon clicking on any category the user will see all the tasks in that group.
我尝试使用 ToDo 列表应用程序进行测试,该应用程序在欢迎屏幕上显示用户创建的任务类别,单击任何类别后,用户将看到该组中的所有任务。 I tried to create a generic class something like
ToDoListViewController<T: NSManagedObject>
and to implement functionality available for both view controllers( CategoryViewController
, TaskViewController
).我试图创建一个通用的 class 类似
ToDoListViewController<T: NSManagedObject>
并实现两个视图控制器( CategoryViewController
, TaskViewController
)可用的功能。 In that class I created a function loadItems
which takes a predicate
as an argument and populates the page with items from a fetch request.在该 class 中,我创建了一个 function
loadItems
,它将predicate
作为参数并使用来自获取请求的项目填充页面。 So the code roughly looks like this:所以代码大致是这样的:
class ToDoListViewController<T: NSManagedObject>: UITableViewController {
func loadItems(predicate: NSPredicate? = nil) {
let request: NSFetchRequest<T> = T.fetchRequest()
if predicate != nil {
request.predicate = predicate!
}
do {
let items = try context.fetch(request)
// Do something
} catch {
print("Error fetching items from context \(error)")
}
}
}
The issue is that when I try to compile I get error:问题是当我尝试编译时出现错误:
Cannot assign value of type
NSFetchRequest<NSFetchRequestResult>
to typeNSFetchRequest<T>
无法将
NSFetchRequest<NSFetchRequestResult>
类型的值分配给NSFetchRequest<T>
类型
when assigning request
variable.分配
request
变量时。 But if I force cast NSFetchRequest<NSFetchRequestResult>
to NSFetchRequest<T>
like this:但是,如果我像这样强制将
NSFetchRequest<NSFetchRequestResult>
转换为NSFetchRequest<T>
:
let request: NSFetchRequest<T> = T.fetchRequest() as! NSFetchRequest<T>
everything works fine.一切正常。 Since The
NSManagedObject
documentation clearly states that it conforms to NSFetchRequestResult
protocol, why do I have to force cast NSFetchRequest<NSFetchRequestResult>
to NSFetchRequest<T>
?由于
NSManagedObject
文档明确声明它符合NSFetchRequestResult
协议,为什么我必须强制将NSFetchRequest<NSFetchRequestResult>
强制转换为NSFetchRequest<T>
?
You have to cast the type because the generic type of NSFetchRequest
– which is constrained to NSFetchRequestResult
– can also be NSDictionary
or NSNumber
or NSManagedObjectID
.您必须转换类型,因为
NSFetchRequest
的泛型类型(受限于NSFetchRequestResult
)也可以是NSDictionary
或NSNumber
或NSManagedObjectID
。
Rather than making a generic type more generic I recommend to use a protocol with associated types like described here我建议使用具有关联类型的协议,而不是使泛型类型更通用,如此处所述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.