如何迅速在closures中抛出错误?

请看下面的代码:

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 } 

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

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

因为你的catch子句并不详尽,所以编译器正在把throws添加到块的签名中:模式匹配let error as NSError可能会失败…查看文档

闭包参数的签名是(UITableViewRowAction, NSIndexPath) -> Void ,但是编译器正在推断你提供的闭包的types(UITableViewRowAction, NSIndexPath) throws -> Void

通过在已经有编译器的编译器之后添加另一个catch子句(没有模式),将会看到你正在本地捕获exception,并且不再推断你正在提供的闭包的签名包括:

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

不可能的,因为闭包可以在任何时候调用,可能不是在你的函数的执行时间,所以错误传播到哪里?

你必须调用另一个可以处理错误的函数:

 func handleError(error: ErrorType) { switch error { ... } } 

然后调用这个函数,在closures中发现你的错误