I am trying to accomplish the following:
I have an enum
enum MyEnum {
case Position(x: Int, y: Int)
case Name(String)
}
and I want to be able to do the following:
MyEnum.caseCount // returns 2
let val = MyEnum.Position(x: 0, y: 0)
val.idx // returns 0
MyEnum.Name("My awesome name").idx // returns 1
So I want a variable holding the total amount of cases + on a specific enum case I want to know its index in the enum
Is there a way I can automatically derive this (probably will be using a protocol)?
I have looked at CaseIterable
, but that can't automatically be implemented for enums holding values. I also can't do = enum MyEnum: Int
because of the value again.
Another SO question had a lot of answers, all implented in Swift 3, and none of those seemed to still work.
If unsafe code would have to be used for this, I would be ok with that.
Something like this would work ofcourse, however it is a lot of boilerplate for the user to write:
extension MyEnum {
func id() -> Int {
switch self {
case .Position: return 0
case .Name: return 1
}
}
}