ios - 条件绑定(bind)的初始化程序必须具有 Optional 类型,而不是 'NSManagedObjectContext

标签 ios xcode swift

我收到此错误消息:“条件绑定(bind)的初始化程序必须具有可选类型,而不是‘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
        }
    }

最佳答案

如果你想强制向下转换(as!),那么你不需要使用可选的绑定(bind)(if let),因为你的应用委托(delegate)将被强制展开。如果 managedObjectContext 是非可选的,那么它就不能解包,这就是编译器所说的。但是,如果您想在可选绑定(bind) (if let) 中安全地解包它,您可以通过条件向下转换 (as?) 和可选链接 ( ?。):

if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext {
    // Do something with managedObjectContext...
}

关于ios - 条件绑定(bind)的初始化程序必须具有 Optional 类型,而不是 'NSManagedObjectContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31690216/

相关文章:

iphone - 打字时键盘挡住屏幕

objective-c - 为什么iOS模拟器会对此暂停?

ios - 无法将 Player 类型的值分配给 SKSpriteNode 类型

iphone - 删除 NSDocumentDirectory 中的图像

IOS 10 objectForKey ("key") 兼容性

ios - 如何使用 .whereKey() 函数访问 Parse 中另一个类中的指针列?

ios - UIImage 到 PHAsset

ios - 此类对于 key screenNumber 不符合键值编码

objective-c - NSError * 与 NSError **

ios - 更新 iOS 中 UI 元素的单元测试方法