Enumerations in Actionscript 3

5 11 2009

Coming from a .Net sort of background, when typing in ‘enum’ into an Actionscript 3 file, I was baffled when it didn’t turn blue! Enumerations are such useful things, I was surprised they weren’t supported in every programming language!

However in Actionscript 3 there is a way to create a class that mimics an enumeration using static constant variables. The code is as follows:

public class CountryCode
{
    public static const UK:int = 1;
    public static const US:int = 3;
    public static const AUS:int = 4;
}

You can then access the “enumeration” as normal:

var whichCountry:int = CountryCode.UK;

Advertisements

Actions

Information

2 responses

30 11 2009
Cardin

There’s a way to have some sort of Enumeration ability in Actionscript.

http://scottbilas.com/2008/06/01/faking-enums-in-as3/
There’s some details on enumerations here. Basically we create an enumeration out of a class, then build the members of the enumeration out of itself. Using the base class Enumerable, we can query and retrieve String or numeric values interchangably.

I also have a modified class based on his work:

//Enumerable.as
package Lib
{
/*
* Enumerable.as
* Dated 25 Aug 2009
* —————
* Faux enumerations in Actionscript. Done through code reflection and static initializers.
*
* Adapted from:
* http://scottbilas.com/2008/06/01/faking-enums-in-as3/
* Scott Bilas – For his wonderful enumeration function.
* Hadrien – For the idea for type-checking the constants.
*
* By: Cardin Lee
* http://cardinal4.co.cc/
*
* —————————– USAGE ——————————
* To use this, you need to include a static initializer within the constructor of the
* class you want to make into an Enumerator.
*
* For instance, for an Enumeration called DaysInWeek, it will look like this:

import Lib.Enumerable;

public class DaysInWeek extends Enumerable
{
public static const MONDAY:DaysInWeek = new DaysInWeek();
public static const TUESDAY:DaysInWeek = new DaysInWeek();
public static const WEDNESDAY:DaysInWeek = new DaysInWeek();
public static const THURSDAY:DaysInWeek = new DaysInWeek();
public static const FRIDAY:DaysInWeek = new DaysInWeek();
public static const SATDAY:DaysInWeek = new DaysInWeek();
public static const SUNDAY:DaysInWeek = new DaysInWeek();

{
initEnum(DaysInWeek);
}
}
*/

import flash.utils.describeType;
import flash.utils.getQualifiedClassName;

/**
* Assists in the creation of faux enumeration datatypes.
*/
public class Enumerable
{
private var constName:String;
protected var index:uint;

/**
* Initializes the specified class object into a faux enumeration datatype.
*
* @param inType The class object that you wish to initialize.
*/
protected static function initEnum(classObj:*):void
{
var type:XML = describeType(classObj);
var className:String = getQualifiedClassName(classObj);

// sort ALPHABETICALLY into an array
var tempList:Array = new Array();
for each (var tempConst:XML in type.constant)
{
// Verify that we don’t anyhow change any constant.
if (tempConst.@type == className)
{
tempList.push(tempConst.@name);
}
}
tempList = tempList.sort();

var i:int = 0;
for each (var constant:String in tempList)
{
classObj[constant].constName = constant;
classObj[constant].index = i;
i++;
}
}

/**
* Retrieves a constant from an constant class based on its string value.
*
* @param value The string value of the constant.
* @param classObj The constant class to which the constant belongs to.
* @return The constant itself.
* @see #retriveValue()
*/
public static function stringRetrieveValue(value:String, classObj:Class):Enumerable
{
value = StringUtils.trim(value);
value = StringUtils.capitalize(value, true);

var type:XML = describeType(classObj);
var className:String = getQualifiedClassName(classObj);

for each (var constant:XML in type.constant)
{
if (constant.@type == className)
{
if (classObj[constant.@name].toString() == value)
return classObj[constant.@name];
}
}
return null;
}

/**
* Retrieves a constant from an constant class based on its numerical value.
*
* @param value The numerical value of the constant.
* @param classObj The constant class to which the constant belongs to.
* @return The constant itself.
* @see #stringRetrieveValue()
*/
public static function retrieveValue(value:uint, classObj:Class):Enumerable
{
var type:XML = describeType(classObj);
var className:String = getQualifiedClassName(classObj);

for each (var constant:XML in type.constant)
{
if (constant.@type == className)
{
if (classObj[constant.@name].index == value)
return classObj[constant.@name];
}
}
return null;
}

/**
* Name of the constant.
*
* @return The string representation of the specified constant.
* @see #valueOf()
*/
public function toString():String
{
var tempName:String = constName.toLowerCase();
var tempArray:Array = tempName.split(“_”);
tempName = tempArray.join(” “);
tempName = StringUtils.trim(tempName);
tempName = StringUtils.capitalize(tempName, true);

/*tempName = tempArray[0];
tempName = tempName.charAt(0).toUpperCase().concat(tempName.slice(1));
for (var i:int = 1; i < tempArray.length; i++)
{
var tempArrayTxt:String = tempArray[i];
tempArrayTxt = tempArrayTxt.charAt(0).toUpperCase().concat(tempArrayTxt.slice(1));
tempName += " " + tempArrayTxt;
}*/

return tempName;
}

/**
* Value of the constant.
*
* @return The numerical representation of the specified constant.
* @see #toString()
*/
public function valueOf():uint
{
return index;
}
}

}

// Helper class StringUtils.as
package {

/**
* String Utilities class by Ryan Matsikas, Feb 10 2006
*
* Visit http://www.gskinner.com for documentation, updates and more free code.
* You may distribute this code freely, as long as this comment block remains intact.
*/

public class StringUtils {

/**
* Capitalizes the first word in a string or all words..
*
* @param p_string The string.
* @param p_all (optional) Boolean value indicating if we should
* capitalize all words or only the first.
*
* @returns String
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function capitalize(p_string:String, …args):String {
var str:String = trimLeft(p_string);
if (args[0] === true) { return str.replace(/^.|\b./g, _upperCase);}
else { return str.replace(/(^\w)/, _upperCase); }
}

/**
* Removes whitespace from the front and the end of the specified
* string.
*
* @param p_string The String whose beginning and ending whitespace will
* will be removed.
*
* @returns String
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function trim(p_string:String):String {
if (p_string == null) { return ''; }
return p_string.replace(/^\s+|\s+$/g, '');
}

/**
* Removes whitespace from the front (left-side) of the specified string.
*
* @param p_string The String whose beginning whitespace will be removed.
*
* @returns String
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
private static function trimLeft(p_string:String):String {
if (p_string == null) { return ''; }
return p_string.replace(/^\s+/, '');
}

private static function _upperCase(p_char:String, …args):String {
return p_char.toUpperCase();
}
}
}

30 11 2009
Sarah

Brilliant thanks very much for posting this. Will try and implement this in any future code where I need enumerations!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: