Accessing a String Enum by Index

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.

How to access a specific member in Java enum by Index value?

Your code nearly works. Take a close look at the method signature of Enum#values (documentation).

It is no method that accepts an argument, it returns the whole array. So you need to shift the access after the method as array-access:

Season.values()[2]

You should avoid accessing Enum by index. They depend on their order in the code. If you do some refactoring like "sort project alphabetical":

public enum Season {
FALL, // 3 -> 0
SPRING, // 1 -> 1
SUMMER, // 2 -> 2
WINTER // 0 -> 3
}

or later add some values to your enum without remembering your order-depend code, then you will break your code. Instead you may setup a Map<Integer, Season>:

Map<Integer, Season> indexToSeason = new HashMap<>();
indexToSeason.put(0, Season.WINTER);
indexToSeason.put(1, Season.SPRING);
indexToSeason.put(2, Season.SUMMER);
indexToSeason.put(3, Season.FALL);

And then use that map for access:

public Season getSeasonByIndex(int index) {
return indexToSeason.get(index);
}

How do I access Typescript Enum by ordinal

When you declare that something is of type NubDirection then it's actually a number:

var a = NubDirection.INWARD;
console.log(a === 1); // true

When you access the enum using the ordinal you get back a string and not a number and because of that you can not assign it to something that was declared as NubDirection.

You can do:

nub.direction = NubDirection[NubDirection[index]];

The reason for this is that there's no such thing as enum in javascript, and the way typescript imitates enums is by doing this when compiling it to js:

var NubDirection;
(function (NubDirection) {
NubDirection[NubDirection["OUTWARD"] = 0] = "OUTWARD";
NubDirection[NubDirection["INWARD"] = 1] = "INWARD";
})(NubDirection || (NubDirection = {}));

So you end up with this object:

NubDirection[0] = "OUTWARD";
NubDirection[1] = "INWARD";
NubDirection["OUTWARD"] = 0;
NubDirection["INWARD"] = 1;

Python - How to get Enum value by index

IIUC, you want to do:

from enum import Enum

class days_of_the_week(Enum):
monday = 0
tuesday = 1
wednesday = 2
thursday = 3
friday = 4
saturday = 5
sunday = 6

>>> days_of_the_week(1).name
'tuesday'

Getting enum Values by its index

You can't get the string representation of an enum in c++.

You have to store them somewhere else.

Example

enum food{PIZZA, BURGER, HOTDOG}

char* FoodToString(food foodid)
{
char* foodStrings[3] = {"PIZZA","BURGER","HOTDOG"};

return foodstrings[foodid];
}

Get index of enum from string?

Not sure if I understand you correctly but based on question title you may be looking for

YourEnum.valueOf("VALUE").ordinal();
  1. YourEnum.valueOf("VALUE") returns enum value with name "VALUE"
  2. each enum value knows its position (indexed from zero) which we can get by calling ordinal() method on it.

How to get Enum Value from index in Java?

Try this

Months.values()[index]

How do I access the an element in an enumeration by the associated number in C?

The enums are nothing but named constants in C. Same as you declare a const using

#define PASTA 0
#define PIZZA 1
#define DIET_COKE 2
#define MOJITO 3

for example.

With the enum the compiler does that for you automatically. So there is no way to access enums in a way you want in C, unless you create an array for them.

Update for an example

An example use case to show how do you implement a string list with the accompany of enum as index:

#include <stdio.h>

char *stringsOfMenu[] = {
"Pasta",
"Pizza",
"Diet Coke",
"Mojito"
};

enum menuIndex {
PASTA,
PIZZA,
DIET_COKE,
MOJITO
};

int main(void) {

// For example you show menu on the screen first
puts("Please select");
puts("-------------");
for(int i = 0; i <= MOJITO; i++) {
printf("[%d] - %s\n", i+1, stringsOfMenu[i]);
}
putchar('\n');
printf("Make a choice: ");
int choice = -1;
scanf("%d", &choice);

if(choice <= 0 || choice > MOJITO+1) {
puts("Not a valid choice");
return 1;
}

// Note that the choice will contain the counting number.
// That's why we convert it to the index number.
printf("Your choice %s is in progress, thank you for your patience!\n", stringsOfMenu[choice-1]);
return 0;
}

This is an output demo:


Please select
-------------
[1] - Pasta
[2] - Pizza
[3] - Diet Coke
[4] - Mojito

Make a choice: 2
Your choice Pizza is in progress, thank you for your patience!



Related Topics



Leave a reply



Submit