I’m cleaning up some AS3 code today, and want to replace a bunch of messy if/else if/else statements with a switch statement.
private const myConstant:int = 3;
private var someNumber:int = 1000;
for(var i:int=0; i < someNumber; i++){
switch(i, myConstant){
case 0:
function1();
break;
case (i % myConstant == 0):
function2();
break;
default:
function3();
}
}
My program has many more case statements and variables, however, I cut it down for the sake of brevity. In this example, I want to call function2() on every third iteration of the loop. Now, myConstant is an important setting for the class which is used elsewhere, so I can’t just put a literal 3 in the expression.
- Can I evaluate multiple variables (and constants) in one switch?
- Can I evaluate expressions such as the second case statement in my example?
The
switchkeyword takes only one expression inside the parentheses (your comma separated variables above would not evaluate to one expression).The
casekeyword also expects to evaluate one expression.In your example, it’s unnecessary to pass either
iormyConstantinto the switch statement. These vars are declared immediately above theswitchand are accessible to any code inside theswitchstatement.Perhaps you want something like this: