switch expression
- Dart course
- Intermediate
- Lesson 74/116
- 5 min
Learn expressions with switch expressions.
The switch expression
A switch expression matches a value against patterns and produces a result. Syntax: String label = switch (n) { 0 => 'zero', _ => 'other' };. Here _ catches all values.
Each arm is a pattern and a result. The expression on the right of => becomes the result. The compiler requires all cases to be covered.
Because a switch expression is an expression, you can assign it to a variable or pass it straight to print.
Switch with patterns
A switch expression can use record and list patterns. Example: switch (p) { (0, _) => 'x zero', (_, 0) => 'y zero', _ => 'valued' }.
Here (0, _) matches records whose first field is 0. _ means ignore that field.
Dart tries patterns top to bottom and returns the first matching arm. Order matters.
Practice Day name
In main declare int day = 3;. Use a switch expression with arms 1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', _ => 'Unknown' to print the day name with print.
Starter code
void main() {
int day = 3;
// print the day name with a switch expression
}Sample solution
void main() {
int day = 3;
print(switch (day) {
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
_ => 'Unknown',
});
}Expected output
Wednesday
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 switch expression body
var label = switch (n) {
0 => 'sıfır',
____ => 'diğer',
};
var label = switch (n) {
0 => 'sıfır',
_ => 'diğer',
};
Explanation: _ catches all remaining values.
2 switch (n) { 0 => 'a', _ => 'b' } for n=5?
- 'a'
- 'b' Correct answer
- Empty string
- Error
Explanation: 5 does not match 0 so the _ arm runs and returns 'b'.
3 What does a switch expression return?
- Always null
- Only void
- A value Correct answer
- A Future
Explanation: a switch expression produces a value.