typestar

Expresiones switch en Dart

El switch de Dart 3 produce un valor, con patrones relacionales y _.

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');
  }
}

Cómo funciona

  1. switch (windKts) como expresión asigna el brazo que coincida.
  2. < 6 y >= 6 && < 22 son patrones relacionales; _ es el defecto.
  3. La forma de sentencia sigue existiendo para efectos por caso.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
19
Caracteres a escribir
482
Tokens
100
Ritmo de tres estrellas
65 tpm

Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 92 segundos.

Escribe este fragmento

Paso 2 de 3 en Control de flujo; paso 5 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →