0

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.

  1. Can I evaluate multiple variables (and constants) in one switch?
  2. Can I evaluate expressions such as the second case statement in my example?

1 Answer 1

2

The switch keyword takes only one expression inside the parentheses (your comma separated variables above would not evaluate to one expression).

The case keyword also expects to evaluate one expression.

In your example, it's unnecessary to pass either i or myConstant into the switch statement. These vars are declared immediately above the switch and are accessible to any code inside the switch statement.

Perhaps you want something like this:

for (var i:int = 0, i < someNumber; i++)
{
    switch (true)
    {
        case i == 0:
            function1();
            break;
        case i % myConstant == 0:
            function2();
            break;
        default:
            function3();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.