Thursday, October 29, 2009

Comparisons with switch/case

The switch and case statements in Actionscript are a useful way of making nested if statements more readable in your code. However they do have one drawback in that the compiler won't allow you to make comparisons. For example, the following code will always skip over the case statements and return the default value:
var myVar:Number = 15;
switch (myVar) {
case (myVar > 0 && myVar < 11) :
trace("between 0-10");
break;
case (myVar > 10 && myVar < 21) :
trace("between 10-20");
break;
case (myVar > 20 && myVar < 31) :
trace("between 21-30");
break;
default : <-- always returns the default value
trace("number outside of range");
break;
}

If you try to remove the references to myVar, the compiler will provide a number of error messages, along the lines of 'case' statements can only be used inside of a 'switch' statement, or Unexpected '>' encountered:

case ( > 0 && < 11) : // <-- gives an error
case > 10 && < 21 : // <-- gives an error

Fortunately it is still possible to perform comparisons by using a Boolean value as the switch expression:
var myVar:Number = 15;
switch (true) { // <-- note the Boolean value here
case (myVar > 0 && myVar < 11) :
trace("between 0-10");
break;
case (myVar > 10 && myVar < 21) :
trace("between 10-20");
break;
case (myVar > 20 && myVar < 31) :
trace("between 21-30");
break;
default :
trace("number outside of range");
break;
}