为什么我不能使用闭包创建 Fetched Results Controller?

Why can't I create a Fetched Results Controller using a closure?

我正在尝试按照一些教程创建一个 Fetched Results Controller。但是,在 Swift 3 中,当我尝试按照您在下面看到的模式创建一个时,出现错误 'unable to infer complex closure type'。

class FriendsController: UICollectionViewController {

lazy var fetchedResultsController: NSFetchedResultsController = {
    let context = (UIApplication.shared.delegate as! 
AppDelegate).persistentContainer.viewContext

    let fetchRequest: NSFetchRequest = Friend.fetchRequest()

    let fetchedResultsController = 
NSFetchedResultsController(fetchRequest: fetchRequest, 
managedObjectContext: context, sectionNameKeyPath: nil, cacheName: 
nil)
    return fetchedResultsController
}()

我在制作视图、按钮等其他内容时使用此闭包模式,但它不起作用(即使我不使用惰性变量)。这个错误对我来说也不是很清楚(如上所述)。谢谢。

NSFetchedResultsController 在 Swift 中是通用的 3. 你必须指定具体类型,因为编译器 无法推断复杂的闭包类型 :

lazy var fetchedResultsController: NSFetchedResultsController<Friend> = { ...

因为您应该指定 FetchedResultsControllers 持有的对象的通用类型

lazy var fetchedResultsController: NSFetchedResultsController<Friend> = {

    let context = //your context

    let req = // your request

    let fetchedResultsController = NSFetchedResultsController(fetchRequest: req, managedObjectContext:context, sectionNameKeyPath: nil, cacheName: nil)
    fetchedResultsController.delegate = self

    do {
        try fetchedResultsController.performFetch()

    }
    catch {
        print("fetch error \(error)")
    }
    return fetchedResultsController
}()