【问题标题】:Handling an Error with custom parameter in an if-statement in Swift在 Swift 的 if 语句中使用自定义参数处理错误
【发布时间】:2017-03-03 17:25:47
【问题描述】:

我在 Swift 中创建了一个符合 Error 的自定义枚举:

enum CustomError: Error{
    case errorWith(code: Int)
    case irrelevantError
}

CustomError 可以选择通过闭包从异步函数返回,如下所示:

func possiblyReturnError(completion: (Error?) -> ()){
    completion(CustomError.errorWith(code: 100))
}

我现在想检查闭包中返回的CustomError 的类型。除此之外,如果是CustomError.errorWith(let code),想提取那个CustomError.errorWith(let code) 的代码。所有这些我都希望使用 if 语句的条件来完成。大意是这样的:

{ (errorOrNil) in
    if let error = errorOrNil, error is CustomError, // check if it is an 
    //.errorWith(let code) and extract the code, if so
    {
        print(error)
    }
    else {
        print("The error is not a custom error with a code")
    }
} 

这完全可能使用 Swift 3.0 吗?我尝试了我能想到的各种组合,但是,所有尝试都没有结果,并以编译时错误告终。

【问题讨论】:

  • 你想在哪里比较错误代码?您的意思是,通过检查错误代码,您想返回一些自定义错误消息?
  • 差不多就是这样。对于CustomError.errorWith(let code) 这两种情况和任何其他错误,我想以不同的方式处理错误。 @金刚狼

标签: ios swift error-handling swift3


【解决方案1】:

使用switch 表达式

 if let error = error as? CustomError {
    switch error {
      case .errorWith(let code):
        print("error has code:" code)
      case .irrelevantError:
        print("irrelevantError")
    }

 } else if error != nil {
    print("The error is not a custom error with a code")
 }

【讨论】:

  • 当然,switch 表达式可以工作。但是,由于我想明确地只对一种特定类型的错误采取行动,而其他类型得到不同的“处理”,我想说,我更喜欢@user28434 解决方案。
【解决方案2】:

这样做

{ (errorOrNil) in
    if let error = errorOrNil as? CustomError, case let .errorWith(code) = error {
       print(code, error)
    } else {
       print("The error is not a custom error with a code")
    }
}

或者使用switch 代替if

【讨论】:

    猜你喜欢
    • 2017-02-17
    • 2021-10-26
    • 2016-05-20
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2011-10-14
    相关资源
    最近更新 更多