Switch in ActionScript

Our example will demonstrate how to use switch statements that express conditionals across many branches.

Here’s a basic switch in ActionScript.

package {
    import flash.display.Sprite;
    import flash.utils.*;
    
    public class SwitchExample extends Sprite {
        public function SwitchExample() {
            var i:int = 2;
            trace("Write " + i + " as ");
            
            switch (i) {
                case 1:
                    trace("one");
                    break;
                case 2:
                    trace("two");
                    break;
                case 3:
                    trace("three");
                    break;
            }
            
            // Using multiple expressions in the same case and the optional default case
            var day:String = new Date().day.toString();
            
            switch (day) {
                case "6":
                case "0":
                    trace("It's the weekend");
                    break;
                default:
                    trace("It's a weekday");
            }
            
            // switch without an expression
            var t:Date = new Date();
            switch (true) {
                case (t.hours < 12):
                    trace("It's before noon");
                    break;
                default:
                    trace("It's after noon");
            }
            
            // A type switch
            whatAmI(true);
            whatAmI(1);
            whatAmI("hey");
        }
        
        private function whatAmI(i:*):void {
            switch (typeof(i)) {
                case "boolean":
                    trace("I'm a bool");
                    break;
                case "number":
                    trace("I'm an int");
                    break;
                default:
                    trace("Don't know type " + i.constructor);
            }
        }
    }
}

To run the program, compile and run your ActionScript code using Adobe Flash or Apache Flex.

$ mxmlc SwitchExample.as
$ fdb
(fdb) run SwitchExample
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type String

Now that you understand how to use switch statements in ActionScript, let’s explore more functionalities of the language.