如何在swift中的闭包中抛出错误? [英] how to throw errors in a closure in swift?

查看:2058
本文介绍了如何在swift中的闭包中抛出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下代码:

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

let deleteAction = UITableViewRowAction(style:UITableViewRowActionStyle.Default,title:Delete,handler:{
(action:UITableViewRowAction,indexPath:NSIndexPath) - & b
if let managedObjectContext =(UIApplication.sharedApplication()。delegate as!AppDelegate).managedObjectContext {
let restaurantToDelete = self.fetchResultController.objectAtIndexPath(indexPath)as!Restaurant
managedObjectContext.deleteObject restaurantToDelete)

//保存managedObjectContext实例,如果失败,捕获错误
do {
try managedObjectContext.save()
} catch let错误为NSError {
print(Error:\(error.localizedDescription))
}

}

})
return deleteAction

来自Xcode的错误消息是:无效的转换类型的抛出函数(UITableViewRowAction,NSIndexPath )throws - > Void'to non-throwing function type'(UITableViewRowAction,NSIndexPath) - > Void'



我知道问题是managedObjectContext.save并且这是不允许在完成处理程序中。我发现一些博客文章,他们修改了闭包参数,以使闭包中的错误处理可行。虽然这里的函数的定义是由苹果,所以我如何解决这个问题?非常感谢! :D

解决方案

编译器正在将 throws 添加到因为你的 catch 子句不是穷举:模式匹配让错误作为NSError 可能失败...看到< a href =https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID512 =nofollow >文档



closure参数的签名为(UITableViewRowAction,NSIndexPath) - > Void ,但是编译器推断你提供的闭包的类型是(UITableViewRowAction,NSIndexPath)throws - >通过在一个之后添加另一个 catch 子句(无模式),使



<已经有编译器会看到你在本地捕获异常,它不会再推断你提供的闭包的签名包括 throws

  do {
try managedObjectContext.save()
} catch let错误为NSError {
print( \(error.localisedDescription))
} catch {}


Please look at the following code:

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
}

the error message from Xcode is : Invalid conversion from throwing function of type '(UITableViewRowAction, NSIndexPath) throws -> Void' to non-throwing function type '(UITableViewRowAction, NSIndexPath) -> Void'

I know the problem is managedObjectContext.save() will throw errors and this is not allowed in the completion handler. I found some blog articles where they modified the closure parameters in order to make the error handling in a closure workable. While here the definition of the function is given by apple, so how can i fix this issue? Thanks a lot! :D

解决方案

the compiler is adding throws to the signature of your block because your catch clause is not exhaustive: the pattern match let error as NSError can fail... see the documentation

the signature of the closure argument is (UITableViewRowAction, NSIndexPath) -> Void, however the compiler is inferring the type of the closure that you are providing to be (UITableViewRowAction, NSIndexPath) throws -> Void

by adding another catch clause (with no pattern) after the one you already have the compiler will see that you are catching the exception locally and it will no longer infer that the signature of the closure you are providing includes throws:

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

这篇关于如何在swift中的闭包中抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆