The Conditional Switch Statement Complete with Case Operators
Posted: April 22, 2010 at 11:02 amHow awesome would it be if we could put conditional code in our switch statements other then strict equality? I'd love to be able to throw some inline operators in my case code like:
var value:int = 2; switch(value){ case < 1: trace("Value is less than 1"); break; case 2: trace("Value definitely equals 2"); break; case >= 3: trace("Value is greater than or equal to 3"); break; case > 1 && < 3: trace("Value is greater than 3 and less than 5"); break; case !== 5: trace("Value definitely doesn't equal 5"); break; }
This would be even cooler if we threw it in a loop. SO how bout it Adobe?
UPDATE: Hector emailed me his code. Pretty cool workaround that does the trick.
var value:int = 2; switch (true) { case value < 1: trace("Value is less than 1"); break; case value == 1: trace("Value equals 1"); break; case value > 1: trace("Value is greater than 1"); break; }
As cool as this is, I think I'll let my request stand just for the code compactness, but thanks Hector! Great stuff.
The Discussion
see what everyone is saying
VB has this feature. Anyway, you can already make:
switch (true) {
case value < 1:
trace(" 1:
trace("> 1″);
break;
}
It seems the code has been parsed and it doesn't display correctly… Well, the thing is that you can make a switch (true) statement, and use conditionals in each case statement.