if / else

if runs a block only when a condition is true:

temperature: int = 25
if temperature > 20 {
    print("warm")
}

Output:

warm

else and else if

score: int = 72
if score >= 90 {
    print("A")
} else if score >= 70 {
    print("C or better")
} else {
    print("below C")
}

Output:

C or better

The conditions are checked from top to bottom, and only the first block whose condition is true runs. else if can be repeated as often as needed, and the final else is optional.

Rules

  • The condition must be a bool. Numbers, strings and lists can’t be used as conditions. Compare explicitly:

    count: int = 3
    if count { }          // error: condition must be a bool, got int (compare explicitly, e.g. x > 0)
    if count > 0 { }      // correct
  • Braces are required, even around a single statement.

  • The { goes on the same line as if (or else).

  • else may start a new line:

    x: int = 1
    if x > 5 {
        print("big")
    }
    else {
        print("small")
    }

    Output:

    small
  • Parentheses around the condition are not needed, but they’re allowed: if (x > 5) { }.

  • A common mistake is caught: if x = 5 gives ’=’ assigns a value; use ‘==’ to compare.

Nesting and combining

Blocks can contain more ifs:

x: int = 5
y: int = 10
if x > 0 {
    if y > 0 {
        print("both positive")
    }
}
if x < y && y == 10 {
    print("Both conditions are true")
}

Output:

both positive
Both conditions are true

Variables declared inside a block exist only inside that block. See Scope.

To pick among several values of one thing, match is shorter than a chain of ifs.