Reputation: 127
Given an external enum that I can't change:
enum MyEnum {
case first
case second
}
How would I best make this RawRepresentable, or at least convertible to an Int (or String) ?
I could write an extension to mimic rawValue, but this feels rather clumsy:
extension MyEnum {
enum EnumError: Error {
case invalidValue
}
init (rawValue: Int) throws {
switch rawValue {
case 0:
self = .first
case 1:
self = .second
default:
throw EnumError.invalidValue
}
}
var rawValue: Int {
switch self {
case .first:
return 0
case .second:
return 1
}
}
}
What is a better way?
Upvotes: 3
Views: 628
Reputation:
This works:
enum MyEnum {
case first
case second
}
extension MyEnum {
enum MyExtendedEnum:Int {
case first
case second
}
}
Its a bit more cleaner code anyways, and your call is now:
let myVar = MyEnum.MyExtendedEnum.RawValue()
Upvotes: 1