【问题标题】:Initializer for conditional binding must have Optional type, not 'NSManagedObjectContext条件绑定的初始化程序必须具有 Optional 类型,而不是 'NSManagedObjectContext
【发布时间】:2015-10-19 19:55:09
【问题描述】:

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

我不确定如何修复此错误。我认为错误在于“如果让”。

  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
        }
    }

【问题讨论】:

    标签: ios xcode swift


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 2021-04-26
      • 2016-01-27
      • 2018-03-05
      • 1970-01-01
      相关资源
      最近更新 更多