Reputation: 11
I am wondering if there is a way to evaluate several values in the switch expression. For example, I want to apply a case only if there is a match for X and Y. Here is my code:
switch (x,y) {
case x >= 0 && x < 150 && y == 150:
topLeftRight();
break;
case x == 150 && y <= 150 && y > 0:
topRightDown();
break;
case y === 0 && x > 0 && x <= 150:
bottomRightLeft();
break;
case x === 0 && y <= 150 && y >= 0:
bottomLeftUp();
break;
}
Do you know if this is possible with switch? Thanks in advance :)
Upvotes: 1
Views: 60
Reputation: 668
you need an if statement
if(x >= 0 && x < 150 && y == 150)
topLeftRight();
else if(x == 150 && y <= 150 && y > 0)
topRightDown();
else if(y === 0 && x > 0 && x <= 150)
bottomRightLeft();
else if(x === 0 && y <= 150 && y >= 0)
bottomLeftUp();
Case statements are good for checking if a single variable is equal to a list of multiple things. For example:
switch(vehicle.type){
case Boat:
print("This is a boat")
break;
case Car:
print("This is a car")
break;
case default:
print("This is not a boat or a car")
break;
}
When evaluating conditionals, it is best to use an if/else if/else
statement
Upvotes: 2
Reputation: 386680
You could take true
as expression to check against the cases. switch
statement uses strict comparison ===
of expression part and case parts.
switch (true) {
case x >= 0 && x < 150 && y == 150:
topLeftRight();
break;
case x == 150 && y <= 150 && y > 0:
topRightDown();
break;
case y === 0 && x > 0 && x <= 150:
bottomRightLeft();
break;
case x === 0 && y <= 150 && y >= 0:
bottomLeftUp();
break;
}
Upvotes: 2