Swift – Accessing a String Enum by index

enumsswift

I have an enum in C and the index needs to be represented by a String.

How can a Swift enum of String type be used by integer index?

I would like to copy the enum to Swift, set the type to string and define all of the raw values to display text, and then use the C enum value to extract the raw value text for the Swift String enum.

Otherwise I will just create an array of strings.. But the enum would be more usable.

Best Answer

Swift 4.2 introduced CaseIterable which does exactly the same thing without the need to declare an allValues array. It works like this:

enum MyEnum: String, CaseIterable {
    case foo = "fooString"
    case bar = "barString"
    case baz = "bazString"
}

and you can access it's values by

MyEnum.allCases

or a value at a specific index by

MyEnum.allCases[index]