This is pretty close, but I would like to be able to save a value that might be related to it, sort of like C.
enum Errors: Int { case transactionNotFound = 500 case timeout = -1001 case invalidState = 409 case notFound = 404 case unknown init(value: Int) { if let error = Errors(rawValue: value) { self = error } else { self = .unknown } } } Errors(value: 40)
I had to create a custom initializer, otherwise it will be recursive. And you can still create using the rawValue initializer randomly.
This, however, feels more Swifty, I removed the type specifier : Int , which allows the use of related values, now the exceptional case that we are not doing anything special is handled in other :
enum Errors2 { case transactionNotFound case timeout case invalidState case notFound case other(Int) init(rawValue: Int) { switch rawValue { case 500: self = .transactionNotFound case -1001: self = .timeout case 409: self = .invalidState case 404: self = .notFound default: self = .other(rawValue) } } } Errors2(rawValue: 40)
With this, I can get the actual value for the โotherโ error, and I can use rawValue to act just like an int based enum. There is one case statement for matching names, but from now on you can use names and should never refer to numbers.
source share