Using the Switch Conditional in ActionScript 3.0

By Blue_Chi | Flash CS4 | ActionScript 3.0 | Beginner

This tutorial will teach you how to use the Switch statement to be able to execute different codes depending on the value of a specified variable. This is useful for situations where a Flash application is required to take different actions in accordance with a specific circumstance. For example, say you have a website that shows a different background depending on the day of the week. The switch statement allows you to put your code in a format that will execute a specific code depending on the value of a day variable.

Structure of the Switch Statement

The switch statement requires a variable and a case value for which the different actions will be specified. It is written in the following generalized code:

switch (myVariable){

case 1:
statements;
break;

case 2:
statements;
break;

case 3:
statements;
break;

}

In essence, switch statement is a conditional similar to the if conditional. The statement will only execute a code if one of the conditions is satisfied.

Basic Usage - Single Case

The switch conditional is more commonly used with a large number of cases, but it can be used as a single conditional that will only execute the code if the variable provided matches the case in question. For example, the code below will only be executed if the variable month equals "December":

switch (month){

case "December":
trace("Yay, we are in the last month of the year!");
break;
}
You can learn more about the trace() command by reviewing our tutorial on this topic.

Such use is superficial for a switch statement because the same result could be achieved by using an if conditional in a shorter format. However, the power of a switch statement is seen when there is more than one case.

Multiple Cases

It is more likely to use a switch statement with multiple cases so that the a specific code would only be executed for appropriate cases only. In the example code below the window will output a message in one of the designated languages depending on the value of the variable language:

switch (language){

case "English":
trace("Hi!");
break;

case "Arabic":
trace("Ahlan!");
break;

case "Spanish":
trace("Hola!");
break;

}

The code to be executed for each case must end with a break statement, such a statement informs Flash that this is the end of the assigned code, omitting it might not generate any compile time errors, but would lead to a confusing result during playback. The last case does not technically need a break statement, but it is always put for the sake of consistency.

This concludes our tutorial on the switch statement, I hope that you found this tutorial helpful. If you have any questions or comments, feel free to post them at the Republic of Code Forum.

- End of Tutorial