how to throw errors in a closure in swift?

后端 未结 2 1725
别跟我提以往
别跟我提以往 2021-01-14 10:01

Please look at the following code:

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRow         


        
相关标签:
2条回答
  • 2021-01-14 10:22

    Not possible, because the closure can be invoked at any time, probably not at execution time of your function, so where should the error propagate to?

    You have to call out to another function which can handle the error:

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

    and then call this function with your caught error inside the closure

    0 讨论(0)
  • 2021-01-14 10:25

    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 {}
    
    0 讨论(0)
提交回复
热议问题