当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Nil is not compatible with expected argument type '()'

问题描述:

I am new in swift and found that RSSReader code from internet and getting error in swift2.

class func saveManagedObjectContext(managedObjectContext:NSManagedObjectContext)->Bool{

if managedObjectContext.save(nil){

return true

}else{

return false

}

}

Nil is not compatible with expected argument type '()'

Call can throw, but it is not marked with 'try' and the error is not handled

Can anyone tell me how i can fix it in swift2?

Thanks

网友答案:

Remove nil from the argument list. The method managedObjectContext.save() throws an error in case something goes wrong. The right way of doing it is

do{
    try managedObjectContext.save()
    return true
}
catch{
    return false
}
网友答案:

The save() method does not take any parameters, so using nil as a parameter is both redundant and invalid. Also, when calling the save method, it has the possibility of throwing an error, so you have to program your function to handle that possible error, like so:

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

If you have specific errors you want to catch, the syntax is written like so:

catch [errorNameHere] {
    [codeToRun]
}

And if you want to catch multiple errors and run corresponding code, you can write this:

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. */
}

You can read all about error handling in the Swift Documentation here.

分享给朋友:
您可能感兴趣的文章:
随机阅读: