如何在swift 2.0中处理连续多次尝试

bol*_*nad 21 nested try-catch swift2

我有一块代码需要执行2个需要尝试的语句.嵌套try是否更好,每个人都有自己的do {} catch {}

 do { 
     try thingOne()
     do {
         try thingTwo()
     } catch let error as NSError {
          //handle this specific error
     }
 } catch let error as NSError {
      //handle the other specific error here
 } 
Run Code Online (Sandbox Code Playgroud)

...或者将try的包装在一个块中并连续运行它们?

do {

   try thingOne()
   try thingTwo()
} catch let error as NSError {
    //do something with this error
}
Run Code Online (Sandbox Code Playgroud)

第二种情况似乎比第一种情况更容易阅读,但catch如果其中任何一种引发错误,那么它会起作用吗?

然后我需要区分抛出的不同错误,除非错误足够通用,那么它可能无关紧要.查看Apple文档并没有看到任何与此相关的内容.

Leo*_*Leo 22

我认为第二种方式更好

假设我有这两个功能

 func thingOne() throws{
      print("Thing 1")
      throw CustomError.Type1
}
func thingTwo() throws{
    print("Thing 2")

    throw CustomError.Type2

}
enum CustomError:ErrorType{
    case Type1
    case Type2
}
Run Code Online (Sandbox Code Playgroud)

然后我会这样称呼它

   do {
        try thingOne()
        try thingTwo()
    } catch CustomError.Type1 {
        print("Error1")
    } catch CustomError.Type2{
        print("Error2")
    } catch {
        print("Not known\(error) ")
    }
Run Code Online (Sandbox Code Playgroud)

这将记录

Thing 1
Error1
Run Code Online (Sandbox Code Playgroud)

如果thingOne()不抛出错误,它将记录

Thing 1
Thing 2
Error2
Run Code Online (Sandbox Code Playgroud)