Enums are my favorite community developed language feature!!!
UPDATED: I have incorporated all comments into a new version of my demo, and updated the post and source code! Old comments are cleared.
An Enum is a kind of variable that is not natively available in ActionScript 3.0, but can be found in other languages such as C++. Perhaps Enums will be included in the upcoming ActionScript 4.0 when it is released.
Basically – An Enum is a type with a restricted set of values. Typically developers use a string to hold simple state variables such as this;
//USING STRINGS (NOT ENUMS)
public static var STATE_ENABLED : String = "STATE_ENABLED";
public static var STATE_DISABLED : String = "STATE_DISABLED";
private var _currentState_str : String = STATE_ENABLED;
Is this familiar? I’m sure it is. By using the static variable the benefit is that developers are less likely to misspell the name of one of these values due to helpful authortime and compile time errors. However the type is stored as a simple string so the developer *CAN* easily pass the wrong string in there (because ANY string is ‘correct’ to the compiler’). This is where Enums are great. Enums would work like this;
// 1. STRONG TYPED & NICE USAGE
var current_estate : StateEnum = StateEnum.Connecting;
// traces ‘Connecting’. Nice!
trace ("Instance : " + current_estate);
// traces ‘true’
trace ("TypeCheck : " + (current_estate is StateEnum) );
// trace ‘true’ – This is the most common usage.
// Checking if a StateEnum instance matches a kind of StateEnum
trace ("Match? : " + (current_estate == StateEnum.Connecting) );
// 2. PROPERLY THROWS AN ERROR – YOU CAN’T INSTANTIATE StateEnum Outside of StateEnum.as
//var local_enum : StateEnum = new StateEnum ();
- Don’t understand me? I don’t blame you. It’s crazy. Check out the source (See ‘Member Resources’ below).
[private_Free member]Enjoy this members-only content!
- Download the full source