Search code examples
migrationnsfetchedresultscontrollerswift3ios10xcode8

Swift: Unable to infer complex closure type with NSFetchedResultsController


After upgrading my project to Swift 3, the following initializer no longer builds:

1    var fetchedResultsController: NSFetchedResultsController {
2        if _fetchedResultsController != nil {
3            return _fetchedResultsController!
4        }
5        
6        let fetchRequest: NSFetchRequest = MyEntity.fetchRequest()
...

The error was on line 1:

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

Line 6 gives a further error:

"Generic parameter 'MyEntity' could not be inferred"

Solution

  • After some reading, I learned that NSFetchRequest and NSFetchedResultsController are now generic in iOS 10, and Apple advises to explicitly specify their type:

    1    var fetchedResultsController: NSFetchedResultsController<MyEntity> {
    2        if _fetchedResultsController != nil {
    3            return _fetchedResultsController!
    4        }
    5        
    6        let fetchRequest: NSFetchRequest<MyEntity> = MyEntity.fetchRequest()
    ...
    

    And a useful tip (for this and other problems in the Swift 3 migration) was to simply create a new application from a template, in XCode!