21

One thing I really like about AS3 over AS2 is how much more compile-time type-checking it adds. However, it seems to be somewhat lacking in that there is no type-checked enumeration structure available. What's a good (best / accepted) way to do custom enumerated types in AS3?

HanClinto
  • 9,423
  • 3
  • 30
  • 31

5 Answers5

17

your answer after the jump :-)

Enumerations with classes

gltovar
  • 463
  • 4
  • 10
  • while my edit is being reviewed I think this link would be similar to the one originally provided: [Enumerations with classes](http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f2f.html) – gltovar Feb 07 '11 at 21:19
15

Just wanted to share my way

LiraNuna
  • 64,916
  • 15
  • 117
  • 140
1

I recently discovered that as3commons library has a good base helper class Enum for enums implemetation.

d9k
  • 1,476
  • 3
  • 15
  • 28
1

In order to be a true enum it needs to both:

  • Enforce type safety
  • Prevent rogue instances

Few of the simple solutions do both, and the base classes that do are overly complex IMO.

My current favourite is the following style - safe and simple, and shouldn't confuse anyone:

public final class FruitEnum {
    private static const CREATE:Object = {};

    public static const APPLE:FruitEnum = new FruitEnum(CREATE);
    public static const ORANGE:FruitEnum = new FruitEnum(CREATE);
    public static const BANANA:FruitEnum = new FruitEnum(CREATE);

    public function FruitEnum(permission:Object) {
        if (permission !== CREATE){
            throw new Error("Enum cannot be instantiated from outside");
        }
    }
}

CAVEAT: I have seen rare circumstances where a variable initialisation reads an enum const before it set, but in those cases the problem applied equally to other const-based enum emulations.

Joachim Lous
  • 1,316
  • 1
  • 14
  • 22
1

I know, this is a little outdated and does not exactly answer your question, but you might wanna check out Haxe. You can also use it to generate AS3 for you, plus there are many other reasons to use it. But this'd really get off topic...

Gama11
  • 31,714
  • 9
  • 78
  • 100
back2dos
  • 15,588
  • 34
  • 50