【问题标题】:Confused on Error Handling in Swift 3对 Swift 3 中的错误处理感到困惑
【发布时间】:2017-12-13 07:30:09
【问题描述】:

我对 swift3 中的错误处理感到困惑。我尝试这样做“如果 XX 函数出错,然后尝试 YY 函数” 让我告诉你我的尝试:

    class MyClass {
      enum error: Error
      {
        case nilString
      }
      func findURL() {
            do {
                let opt = try HTTP.GET(url_adr!)
                opt.start { response in
                    if let err = response.error {
                        print("error: \(err.localizedDescription)")
                        return //also notify app of failure as needed
                    }
                    do
                    {
/* This is func1. and got error. I want to if this function has error then go next function. */
                            try self.stringOperation(data: response.description)
                        }
                        catch{
                            print("doesn't work on func1. trying 2nd func")
                          self.stringOperation2(data:response.descritption)
                        }

                    }
                } catch let error {
                    print("got an error creating the request: \(error)")
                }
         }
         func stringOperation(data:String)throws -> Bool{
                do{
/** 1 **/
                        if let _:String = try! data.substring(from: data.index(of: "var sources2")!){ 
                            print("its done")
                        }else{
                        throw error.nilString
             }

IN 1:我在这一行遇到了这个致命错误: “致命错误:在展开可选值时意外发现 nil”并且程序崩溃。 我用谷歌搜索了错误处理,试图理解并应用到我的代码中。然而还没有成功。谁能解释我哪里做错了?

附加信息:我得到了 .substring(from:...) 和 .index(of:"str") 的字符串扩展名。所以这些行不会让你感到困惑。

【问题讨论】:

  • 给出程序崩溃或发现的行号 nil
  • 错误行位于“/** 1 **/”消息下方...但是 tbogosia 的答案已解决...谢谢

标签: swift swift3 error-handling


【解决方案1】:

作为一般规则,请尽量避免使用强制展开 (!),您有

if let _: String= try! data.substring...

改为使用

if let index = data.index(of: "var sources2"), 
    let _: String = try? data.substring(from: index) { ... } else { ... }

这样您就可以消除可能导致崩溃的两个强制展开。您已经拥有用于捕获 nil 值的if let 保护,因此您可以通过使用条件展开来充分利用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多