【问题标题】:Swift Nested try inside a closure闭包内的Swift嵌套尝试
【发布时间】:2018-11-28 07:29:36
【问题描述】:

我有以下要求

enum CustomError1: Error {
    case errorA
}

enum CustomError2: Error {
    case errorA
}

public func func1(completion: @escaping () -> Void) throws {
    //some code
    if #somecondition {
        throw CustomError1.errorA
    }
    completion()
}

public func func2(completion: @escaping () -> Void) throws {
    //some code
    if #somecondition {
        throw CustomError2.errorA
    }
    completion()
}


func result() {
    do {
        try func1() {
            try self.func2 (){

            }
        }
    } catch {

    }
}

结果函数给出如下错误

Invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'

那是因为 func1 和 func2 给出了不同类型的错误。

因此,我需要在第一个闭包内写另一个do catch,如下所示

func result() {
    do {
        try func1() {
            do {
                try self.func2 (){

                }
            } catch {

            }
        }
    } catch {

    }
}

有没有办法简化这种嵌套的try catchs

【问题讨论】:

    标签: ios swift error-handling


    【解决方案1】:

    问题在于func1 的参数输入为escaping () -> Void。这意味着您不能在作为该参数传递的函数内抛出。您需要将其输入为escaping () throws -> Void

    【讨论】:

      【解决方案2】:
      enum CustomError1: Error {
          case errorA
      }
      
      enum CustomError2: Error {
          case errorA
      }
      
      public func func1(completion: @escaping () throws -> Void) throws {
          //some code
          if true {
              throw CustomError1.errorA
          }
          try completion()
      }
      
      public func func2(completion: @escaping () throws -> Void) throws {
          //some code
          if true {
              throw CustomError2.errorA
          }
          try completion()
      }
      
      
      func result() {
          do {
              try func1(completion: {
                  try func2 (completion: {
      
                  })
              })
          } catch {
      
          }
      }
      

      我不建议将 throw 与完成一起使用。更好的方法是使用更好的完成实现。像这样的:

      public func func1(completion: @escaping (Error?) throws -> Void) throws {
          //some code
          if true {
              completion(CustomError1.errorA)
          }
         completion(nil)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-14
        • 2017-05-26
        • 2017-05-30
        • 2015-05-09
        相关资源
        最近更新 更多