3

I'm implementing try catch enum:

enum processError: Error, CustomStringConvertible {

        case one
        var localizedDescription: String{
            return "one"
        }
        case two
        var localizedDescription: String {
            return "two"
        }
    }

But I'm getting the following error:

type processError does not conform to protocol CustomStringConvertible

But if I change the name of the variable in the second case I don't get the error:

enum processError: Error, CustomStringConvertible {

    case one
    var localizedDescription: String{
        return "one"
    }
    case two
    var description: String {
        return "two"
    }
}

My question is why I can not have the same name of the variable for all the cases?

I'll really appreciate your help.

shallowThought
  • 19,212
  • 9
  • 65
  • 112
user2924482
  • 8,380
  • 23
  • 89
  • 173
  • Press ⌘4 and click on the disclosure triangle next to the error. You will see: *Protocol requires property `description`...* and you cannot declare a variable with the same name twice (*Invalid redeclaration...* error) – vadian Feb 24 '17 at 20:57
  • Possibly related: [How to provide a localized description with an Error type in Swift?](http://stackoverflow.com/questions/39176196/how-to-provide-a-localized-description-with-an-error-type-in-swift). – Martin R Feb 24 '17 at 21:01
  • @user2924482 `enum ProcessError: String, Error { case one, two var description: String { return rawValue } }` – Leo Dabus Feb 24 '17 at 21:22

1 Answers1

6

The issue is that the CustomStringConvertible protocol requires one property:

var description: String

You need to have the description property or you will get the error that it doesn't conform to the protocol.

I also suggest this approach:

enum processError: Error, CustomStringConvertible {
    case one
    case two

    var description: String {
        switch self {
            case .one:
                return "one"
            case .two:
                return "two"
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Overriding localizedDescription does not work that way (unless you cast an Error to the specific processError), compare above link under the question. – Martin R Feb 24 '17 at 21:06
  • @MartinR Thank. I removed that part of the answer. I'll leave it focused on the protocol issue. – rmaddy Feb 24 '17 at 21:08