Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializer for conditional binding must have Optional type, not 'NSManagedObjectContext

Tags:

xcode

ios

swift

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

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

  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
        }
    }
like image 741
Jorge A Gomez Avatar asked May 11 '26 09:05

Jorge A Gomez


1 Answers

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 (?.):

if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext {
    // Do something with managedObjectContext...
}
like image 200
Patrick Lynch Avatar answered May 14 '26 00:05

Patrick Lynch