无法推断出复杂的闭包返回类型;添加显式类型以消除歧义

时间:2018-05-02 08:08:37

标签: ios swift nsfetchedresultscontroller type-inference

有人知道我怎么能解决这个错误吗?在以下代码块的第一行收到错误:

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
}()

3 个答案:

答案 0 :(得分:7)

尝试在闭包中添加返回类型,如下代码:

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
}()

答案 1 :(得分:3)

错误信息有点误导,问题是你做错了 不指定变量的通用占位符类型。

您可以向闭包添加显式返回类型,如@Mukesh 建议,在这种情况下,变量的类型注释不是 需要:

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

或者完全指定变量的类型,然后关闭返回 类型是自动推断的:

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

答案 2 :(得分:0)

两个问题:

  1. 如其他答案中所述,您必须指定泛型类型,在您的情况下,理想类型是具体的NSManagedObject子类。
  2. 声明NSFetchedResultsController至少需要一个排序描述符

    let fetchedResultsController: NSFetchedResultsController<Message> = {
        let fetchRequest = NSFetchRequest<Message>(entityName: "Message")
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "somekey", ascending: true]
        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
    }()