Evgenii Evgenii - 6 months ago 13
Swift Question

Is there a way to specify an error code for an ErrorType value in Swift?

In my app I am using a custom error type

ProgrammerError
with three error values
.Messiness
,
.Procrastination
and
.Arrogance
(these are just examples). Later in the code I need to cast the errors to
NSError
. The
NSError
objects have
code
properties starting from 0 following the order or error values I declared: 0, 1, 2 etc.

enum ProgrammerError: ErrorType {
case Messiness
case Procrastination
case Arrogance
}

(ProgrammerError.Messiness as NSError).code // 0
(ProgrammerError.Procrastination as NSError).code // 1
(ProgrammerError.Arrogance as NSError).code // 2


My question is: Is there a way to set different error codes for the enumeration values? For example, can I set
Messiness
to have
code
value of 100 instead of 0?

Answer

You can implement var _code: Int { get } property.

enum ProgrammerError: ErrorType {
    case Messiness
    case Procrastination
    case Arrogance

    var _code: Int {
        switch self {
        case .Messiness:
            return 100
        case .Procrastination:
            return 101
        case .Arrogance:
            return 102
        }
    }
}

(ProgrammerError.Messiness as NSError).code // 100
(ProgrammerError.Procrastination as NSError).code // 101
(ProgrammerError.Arrogance as NSError).code // 102

You can also implement var _domain: String { get } if you need.

But I must warn you, these methods are undocumented so they might stop working in future.