【问题标题】:Nil is not compatible with expected argument type '()'Nil 与预期的参数类型 '()' 不兼容
【发布时间】:2016-06-28 22:17:22
【问题描述】:

我是 swift 新手,发现 RSSReader 代码来自互联网,并在 swift2 中出错。

class func saveManagedObjectContext(managedObjectContext:NSManagedObjectContext)->Bool{
        if managedObjectContext.save(nil){
            return true
        }else{
            return false
        }
    }

Nil 与预期的参数类型“()”不兼容
call 可以抛出,但是没有标记'try',错误没有处理

谁能告诉我如何在 swift2 中修复它?
谢谢

【问题讨论】:

    标签: ios swift swift2


    【解决方案1】:

    从参数列表中删除 nil。如果出现问题,managedObjectContext.save() 方法会抛出错误。正确的做法是

    do{
        try managedObjectContext.save()
        return true
    }
    catch{
        return false
    }
    

    【讨论】:

      【解决方案2】:

      save()方法不带任何参数,所以使用nil作为参数既多余又无效。另外,当调用 save 方法时,它有可能抛出一个错误,所以你必须编写你的函数来处理这个可能的错误,像这样:

      func saveManagedObjectContext(managedObjectContext:NSManagedObjectContext)->Bool {
           do {
               try managedObjectContext.save()
               return true
           } catch {
               return false
           }
      }
      

      如果你想捕捉特定的错误,语法是这样写的:

      catch [errorNameHere] {
          [codeToRun]
      }
      

      如果你想捕获多个错误并运行相应的代码,你可以这样写:

      catch [errorNameHere] {
          [codeToRun]
      } catch [anotherErrorNameHere] {
          [codeToRun]
      } catch {
          [defaultCodeToRun] /* if no errors are thrown that were written above, but 
          there is an error thrown, this default catch block will handle it. If there 
          is no catch block to handle an error thrown and no default catch block, the 
          compiler will simply exit without having run anything. */
      }
      

      您可以在 Swift 文档here 中阅读有关错误处理的所有信息。

      【讨论】:

      • class func 是有效代码。它在类型而不是实例上声明一个函数。
      • @dan 哦,好吧。我会解决的。谢谢。
      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多