casillas
casillas

Reputation: 16813

Error comparision - Binary operator == cannot be applied two Error operands

I have got an error as follows

Service Error is as follows:

enum ServiceError: Error {
  case ServerDown
  case UserNotExist
}

My error object is as follows

enter image description here

However, I am getting in the following comparision

Binary operator == cannot be applied two Error operands

Are there any other better solution rather than adding Equatable solution in my case?

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

Upvotes: 1

Views: 154

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236558

You need to cast the Swift.Error to your custom ServiceError. The common approach is to use a switch:

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")
}

Note: It is Swift naming convention to name your enumeration cases starting with a lowercase letter.

Upvotes: 2

Related Questions