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

时间:2021-12-29 17:05:47

I get this error message: "Initializer for conditional binding must have Optional type, not 'NSManagedObjectContext ".

我收到此错误消息:“条件绑定的初始化程序必须具有可选类型,而不是'NSManagedObjectContext”。

I am not sure how to fix this error. The error is with the "if let" I think.

我不知道如何解决这个错误。我认为错误在于“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 个解决方案

#1


6  

If you want to force downcast (as!), then you don't need to use the optional binding (if let) because your app delegate will be force unwrapped. If managedObjectContext is non optional, then it can't be unwrapped, which is what the compiler is saying. But if you want to unwrap it safely in an optional binding (if let), you can achieve this with a condition downcast (as?) and optional chaining (?.):

如果你想强制转发(如!),那么你不需要使用可选绑定(如果允许),因为你的app委托将被强制解包。如果managedObjectContext是非可选的,则无法解包,这是编译器所说的。但是如果你想在一个可选的绑定中安全地打开它(如果让它),你可以通过条件downcast(如?)和可选的链接(?。)来实现:

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

#1


6  

If you want to force downcast (as!), then you don't need to use the optional binding (if let) because your app delegate will be force unwrapped. If managedObjectContext is non optional, then it can't be unwrapped, which is what the compiler is saying. But if you want to unwrap it safely in an optional binding (if let), you can achieve this with a condition downcast (as?) and optional chaining (?.):

如果你想强制转发(如!),那么你不需要使用可选绑定(如果允许),因为你的app委托将被强制解包。如果managedObjectContext是非可选的,则无法解包,这是编译器所说的。但是如果你想在一个可选的绑定中安全地打开它(如果让它),你可以通过条件downcast(如?)和可选的链接(?。)来实现:

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