如何在swift的闭包中抛出错误?

use*_*747 3 error-handling closures ios swift2

请看下面的代码:

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

   let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete", handler: {
        (action : UITableViewRowAction, indexPath : NSIndexPath)  -> Void  in

        if let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext{
            let restaurantToDelete = self.fetchResultController.objectAtIndexPath(indexPath) as! Restaurant
            managedObjectContext.deleteObject(restaurantToDelete)

            // Saving managedObjectContext instance, and catch errors if it fails
            do {
                try managedObjectContext.save()
            } catch let error as NSError {
                print("Error: \(error.localizedDescription)")
            }

        }

    })
    return deleteAction
}
Run Code Online (Sandbox Code Playgroud)

来自Xcode的错误消息是:从类型'(UITableViewRowAction,NSIndexPath)抛出函数的无效转换抛出 - > Void'到非投掷函数类型'(UITableViewRowAction,NSIndexPath) - > Void'

我知道问题是managedObjectContext.save()将抛出错误,这在完成处理程序中是不允许的.我发现了一些博客文章,他们修改了闭包参数,以便在闭包中使错误处理可行.虽然这里函数的定义是由apple给出的,那么我该如何解决这个问题呢?非常感谢!:d

fqd*_*qdn 6

编译器正在添加throws块的签名,因为您的catch子句并非详尽无遗:模式匹配let error as NSError可能会失败...请参阅文档

但是,关闭参数的签名是(UITableViewRowAction, NSIndexPath) -> Void,编译器会推断出您提供的闭包的类型(UITableViewRowAction, NSIndexPath) throws -> Void

通过添加另一个catch子句(没有模式),你已经拥有的编译器将看到你在本地捕获异常,它将不再推断你提供的闭包的签名包括throws:

do {
  try managedObjectContext.save()
} catch let error as NSError {
  print("Error: \(error.localizedDescription)")
} catch {}
Run Code Online (Sandbox Code Playgroud)