switch expressions in Dart
Dart 3's switch yields a value, with relational patterns and _.
void main() {
const windKts = 18;
// A switch expression yields a value; ranges match with relational
// patterns and _ is the default.
final flag = switch (windKts) {
< 6 => 'calm: mist nets up',
>= 6 && < 22 => 'workable breeze',
_ => 'too rough for the ridge',
};
print('Wind $windKts kts: $flag');
// The statement form still works for side effects per case.
switch (flag.split(':').first) {
case 'calm':
print('Listen for warblers');
default:
print('Scan the open water');
}
}
How it works
switch (windKts)as an expression assigns whichever arm matches.< 6and>= 6 && < 22are relational patterns;_is the default.- The statement form still exists for side effects per case.
Keywords and builtins used here
caseconstdefaultfinalswitchvoid
The run, in numbers
- Lines
- 19
- Characters to type
- 482
- Tokens
- 100
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 92 seconds.
Step 2 of 3 in Control flow, step 5 of 27 in Language basics.