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
}
}
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With