iosswiftcore-dataios10

Cannot convert value of type 'NSFetchRequest<NSFetchRequestResult>' to specified type 'NSFetchRequest<T>'


I want to use new Core Data API introduced in iOS10.

@available(iOS 10.0, *)
open class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>

I created generic function to fetching all kinds of objects:

func getAllEntities<T: NSManagedObject>(ofType type: T.Type, success: @escaping ([T]) -> ()) throws -> [T] {
    let fetchRequest: NSFetchRequest<T> = T.fetchRequest()
    let asyncFetchRequest = NSAsynchronousFetchResult(fetchRequest: fetchRequest) { result in
        success(result.finalResult ?? [])
    }

    try databaseStack.persistentContainer.viewContext.execute(asyncFetchRequest)
}

but in line let fetchRequest: NSFetchRequest<T> = T.fetchRequest() I got issue:

Cannot convert value of type 'NSFetchRequest<NSFetchRequestResult>' to specified type 'NSFetchRequest<T>'

What did I do wrong?


Solution

  • T.fetchRequest() returns a NSFetchRequest<NSFetchRequestResult>, you have to explicitly cast it to the specific NSFetchRequest<T>:

    let fetchRequest = T.fetchRequest() as! NSFetchRequest<T>
    let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { result in
        success(result.finalResult ?? [])
    }