Nil与预期的参数类型不兼容'()'

时间:2016-06-28 22:17:23

标签: ios swift swift2

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

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

Nil与预期的参数类型不兼容'()'
  通话可以抛出,但没有标记为'尝试'并且没有处理错误

enter image description here

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分: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中阅读有关错误处理的所有内容。

相关问题