Helium3 Helium3 - 3 months ago 22
Swift Question

Accessing a String Enum by index

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.

Answer

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.