【问题标题】:Error comparision - Binary operator == cannot be applied two Error operands错误比较 - 二元运算符 == 不能应用于两个错误操作数
【发布时间】:2020-10-16 21:01:12
【问题描述】:

我遇到如下错误

服务错误如下:

enum ServiceError: Error {
  case ServerDown
  case UserNotExist
}

我的错误对象如下

但是,我正在进行以下比较

二元运算符 == 不能应用两个错误操作数

在我的情况下,除了添加 Equatable 解决方案之外,还有其他更好的解决方案吗?

if error != nil {
  if error == ServerDown {
    print("ServerDown")
  } else if error == UserNotExist {
    print("User Not Exist")
  } else {
    print("Generic Error")
  }
}

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您需要将Swift.Error 转换为您的自定义ServiceError。常见的做法是使用开关:

    enum ServiceError: Error {
      case serverDown, userNotExist
    }
    

    let error: Error? = ServiceError.serverDown as Error
    
    switch error as? ServiceError {
    case .serverDown: print("Server is down")    // "Server is down\n"
    case .userNotExist: print("User not found")
    case .none: print("error:", error ?? "nil")
    }
    

    注意:使用小写字母开头的枚举案例命名是 Swift 命名约定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-07
      • 2016-04-10
      • 2015-09-01
      • 2017-11-22
      相关资源
      最近更新 更多