条件绑定的初始化器必须具有可选类型,而不是'NSManagedObjectContext'。

3
我收到了这个错误信息:“有条件绑定的初始化器必须具有可选类型,而不是“NSManagedObjectContext”。”
我不确定如何修复此错误。我认为问题出在“if let”语句上。
  if  let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext  {
        restaurant = NSEntityDescription.insertNewObjectForEntityForName("Restaurant",
            inManagedObjectContext: managedObjectContext) as! Restaurant
        restaurant.name = nameTextField.text
        restaurant.type = typeTextField.text
        restaurant.location = locationTextField.text
        restaurant.image = UIImagePNGRepresentation(imageView.image!)
        restaurant.isVisited = isVisited
        //restaurant.isVisited = NSNumber.convertFromBooleanLiteral(isVisited)

        var e: NSError?
        if managedObjectContext.save() != true {
            print("insert error: \(e!.localizedDescription)")
            return
        }
    }
1个回答

7
如果你想要进行强制向下转型(as!),那么你不需要使用可选绑定 (if let),因为你的应用委托将会被强制展开。如果 managedObjectContext 是非可选的,那么它就不能被展开,这就是编译器所指的。但是如果你想要在可选绑定中安全地展开它 (if let),你可以通过条件转换 (as?) 和可选链 (?.) 来实现这一点:
if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext {
    // Do something with managedObjectContext...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接