Switch in Dart

Switch statements express conditionals across many branches.

Here’s a basic switch.

void main() {
    int i = 2;
    print("Write $i as ");
    switch (i) {
        case 1:
            print("one");
            break;
        case 2:
            print("two");
            break;
        case 3:
            print("three");
            break;
    }

    // You can use commas to separate multiple expressions in the same `case` statement. We use the optional `default` case in this example as well.
    switch (DateTime.now().weekday) {
        case DateTime.saturday:
        case DateTime.sunday:
            print("It's the weekend");
            break;
        default:
            print("It's a weekday");
    }

    // `switch` without an expression is an alternate way to express if/else logic. Here we also show how the `case` expressions can be non-constants.
    var t = DateTime.now();
    switch (t.hour) {
        case var hour when hour < 12:
            print("It's before noon");
            break;
        default:
            print("It's after noon");
    }

    // A type `switch` compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable `t` will have the type corresponding to its clause.
    dynamic a = true;
    var b = 1;
    var c = "hey";

    whatAmI(a);
    whatAmI(b);
    whatAmI(c);
}

void whatAmI(dynamic i) {
    if (i is bool) {
        print("I'm a bool");
    } else if (i is int) {
        print("I'm an int");
    } else {
        print("Don't know type ${i.runtimeType}");
    }
}

To run this Dart program, ensure you have Dart installed on your system. Save the code to a file called switch_example.dart and use the dart command to run it.

$ dart switch_example.dart
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type String

This Dart program demonstrates various uses of the switch statement, similar to what is shown in the example code.