Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a String Enum by index

Tags:

enums

swift

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.

like image 715
some_id Avatar asked Sep 03 '16 09:09

some_id


People also ask

Can you index into an enum?

Solution. Yes you can programmatically index an enum, text, or menu ring. An easy way to do this is to type cast the iteration terminal of a While or For Loop to the enum, text, or menu ring that you want to index.

How do you find the index of an enum?

Use the Object. values() method to get an array containing the enum's values. Use square brackets to access the array at the specific index and get the value.

How do you match a string to an enum?

For comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString() method or name() method. toString()- Returns the name of this enum constant, as contained in the declaration.

Can we use string in enum?

In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member. While string enums don't have auto-incrementing behavior, string enums have the benefit that they “serialize” well.


1 Answers

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] 
like image 155
Bogdan Razvan Avatar answered Sep 18 '22 16:09

Bogdan Razvan