Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to infer complex closure return type; add explicit type to disambiguate

Does anybody know how I can solve this error that I'm getting? The error is received on the first line in the following chunk of code:

let fetchedResultsController: NSFetchedResultsController = {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Message")
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    return frc
}()
like image 531
random1234 Avatar asked May 02 '18 08:05

random1234


2 Answers

Try adding the return type in the closure like this code:

let fetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController<NSFetchRequestResult> in
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Message")
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    return frc
}()
like image 128
Mukesh Avatar answered Nov 15 '22 21:11

Mukesh


The error message is a bit misleading, the problem is that you did not specify the generic placeholder type for the variable.

You can either add an explicit return type to the closure, as @Mukesh suggested, in that case the type annotation on the variable is not needed:

let fetchedResultsController = { () -> NSFetchedResultsController<NSFetchRequestResult> in
    // ...
    return frc
}()

Or fully specify the type of the variable, then the closure return type is inferred automatically:

let fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
    // ...
    return frc
}()
like image 41
Martin R Avatar answered Nov 15 '22 19:11

Martin R