'Switch case with multiple values for the same case
I would like to know the syntax to set a multiple case statement in a switch / case.
For example :
String commentMark(int mark) {
switch (mark) {
case 0 : // Enter this block if mark == 0
return "Well that's bad" ;
case 1, 2, 3 : // Enter this block if mark == 1 or mark == 2 or mark == 3
return "Gods what happend" ;
// etc.
default :
return "At least you tried" ;
}
}
I cannot find the right syntax to set multiple case (the line case 1, 2, 3 :
), is it even possible in Dart ?
I did not found any informations on pub.dev documentation, neither on dart.dev.
I tried :case 1, 2, 3
case (1, 2, 3)
case (1 ; 2 ; 3)
case (1 : 2 : 3)
case 1 : 3
and more !
Solution 1:[1]
Execution continues until it reaches a break;
. Therefore, you can list cases one after the other to get the following code execute on either one of those cases.
String commentMark(int mark) {
switch (mark) {
case 0 : // Enter this block if mark == 0
return "mark is 0" ;
case 1:
case 2:
case 3: // Enter this block if mark == 1 or mark == 2 or mark == 3
return "mark is either 1, 2 or 3" ;
// etc.
default :
return "mark is not 0, 1, 2 or 3" ;
}
}
The return
statements above serve to get out of the function. If you do not want to return
, you have to use break;
after each block, of course. This code below is equivalent to the one above.
String commentMark(int mark) {
String msg;
switch (mark) {
case 0 : // Enter this block if mark == 0
msg = "mark is 0" ;
break;
case 1:
case 2:
case 3: // Enter this block if mark == 1 or mark == 2 or mark == 3
msg = "mark is either 1, 2 or 3" ;
break;
// etc.
default:
msg = "mark is not 0, 1, 2 or 3" ;
break; // this is a good habit, in case you change default to something else later.
}
return msg;
}
Solution 2:[2]
Instead of multiple case we can use or operator in single switch case it self.
switch (date) {
case 1 | 21 | 31:
return "st";
case 2 | 22:
return "nd";
case 3 | 23:
return "rd";
default:
return "th";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Abhinay Raj |