views:

93

answers:

3

Is there any way in ActionScript3 to get enum from string value? e.g. I have enum

public final class Day
{
    public static const MONDAY:Day = new Day();
    public static const TUESDAY:Day = new Day();
    public static const WEDNESDAY:Day = new Day();
    public static const THURSDAY:Day = new Day();
    public static const FRIDAY:Day = new Day();
    public static const SATURDAY:Day = new Day();
    public static const SUNDAY:Day = new Day();
}

and I want to get enum Day.MONDAY from string "MONDAY"

A: 

In ActionScript obj.prop is same as obj["prop"] - just confirmed that this applies to static properties too. So you can access it like:

trace(Day["MONDAY"]);
Amarghosh
A: 

or

var day:String="MONDAY";
trace(Day[day]);
frankhermes
A: 

Just to quickly chime in on this for future reference; if you have access to modify the class, a fromString(); method would be preferable as it makes the API clearer for other developers.

public static function fromString(value : String) : Day
{
  switch(value.toLowerCase())
  {
    case "monday":
      return MONDAY;

    case "tuesday":
      return TUESDAY;

    // ...etc

    default:
      throw new ArgumentError(value + " is not a valid value");
      return null;
  }
}
JonnyReeves