The conditional binding initializer must be an optional type, not "NSManagedObjectContext

I am getting this error message: "The initializer for the conditional binding must be an optional type, not" NSManagedObjectContext ".

I'm not sure how to fix this error. The mistake is that "if so" 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
        }
    }

      

+3


source to share


1 answer


If you want to force downcast ( as!

), you don't need to use the optional bind ( if let

) because your app delegate will be disabled. Unless managedObjectContext

it is optional, it cannot be expanded, which is what the compiler says. But if you want to safely deploy it in an optional bind ( if let

), you can achieve it with the downcast ( as?

) condition and the optional chaining ( ?.

):



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

      

+6


source







All Articles