Accessing a String Enum by index

2 Solutions Collect From Internet About “Accessing a String Enum by index”

In Swift, enum types do not hold its index info of cases (at least, not provided for programmers).

So:

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

The answer is “You cannot”.


You can bind Int (or enum cases) and String values in many ways other than just create an array of strings..

For example, if your bound Strings can be the same as case labels, you can write something like this:

enum MyEnum: Int {
    case foo
    case bar
    case baz

    var string: String {
        return String(self)
    }
}

if let value = MyEnum(rawValue: 0) {
    print(value.string) //->foo
}

If your Strings need to be a little more complex to display text, you can use Swift Dictionary to bind enum cases and Strings.

enum AnotherEnum: Int {
    case foo
    case bar
    case baz

    static let mapper: [AnotherEnum: String] = [
        .foo: "FooString",
        .bar: "BarString",
        .baz: "BazString"
    ]
    var string: String {
        return AnotherEnum.mapper[self]!
    }
}

if let value = AnotherEnum(rawValue: 1) {
    print(value.string) //->BarString
}

A little bit more readable than a simple array of strings.

Simple workaround which is also useful if you want to enumerate a string enum.

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

    static let allValues = [foo, bar, baz] //must maintain second copy of values
}

//enumeration advantage
for value in MyEnum.allValues {
    print(value)
}

//get value by index
let value = MyEnum.allValues[1] 

print(value) //barString