Control Flow

6.1 if / else

if (x > 0) writeln("positive");
else if (x < 0) writeln("negative");
else writeln("zero");

auto sign = x > 0 ? "+" : "-";
if (auto p = "key" in aa) writeln(*p);    // declare in a condition

6.2 switch / final switch

Implicit fallthrough is an error. Use goto case; or goto case X; for explicit fallthrough.

You can switch on integers, chars, strings, and enums.

switch (cmd)
{
    case "start":
        start();
        break;
    case "stop", "halt":            // multiple values
        stop();
        break;
    case 1: .. case 9:              // case range (for ints)
        break;
    default:
        writeln("unknown");
}

enum Color { red, green, blue }
final switch (color)                // must handle every enum member; no default
{
    case Color.red: writeln("R"); break;
    case Color.green: writeln("G"); break;
    case Color.blue: writeln("B"); break;
}

6.3 Loops

for (int i = 0; i < 5; i++) writeln(i);

int n = 0;
while (n < 5) n++;
do { n--; } while (n > 0);

foreach (i; 0 .. 5) writeln(i);                    // range: 0..4
foreach (item; [10, 20, 30]) writeln(item);
foreach (i, item; [10, 20, 30]) writefln("%d: %d", i, item);   // with index
foreach (ref item; arr) item *= 2;                 // modify in place
foreach_reverse (i; 0 .. 5) writeln(i);            // 4..0
foreach (key, value; aa) writeln(key, "=", value); // associative array
foreach (dchar c; "héllo") write(c, " ");          // decode UTF-8 to code points

6.4 Labels, break, continue, goto

outer: foreach (i; 0 .. 10)
{
    foreach (j; 0 .. 10)
    {
        if (i * j == 42) break outer;
        if (j > i) continue outer;
    }
}
goto end;
end:

6.5 with Statement

struct Config { string host; int port; }
Config cfg;
with (cfg)
{
    host = "localhost";
    port = 8080;
}
with (Color) { auto c = red; }   // bring enum members into scope