Conditional branching: if-statement

If-statements allow a certain piece of code to be executed only when a given condition is true.

The if-statement starts with the if keyword, followed by the condition, and the code that should be executed if the condition is true inside opening and closing braces. The condition expression must be Bool The braces are required and not optional. Parentheses around the condition are optional.

let a = 0
var b = 0

if a == 0 {
   b = 1
}

// Parentheses can be used around the condition, but are not required.
if (a != 0) {
   b = 2
}

// `b` is `1`

An additional, optional else-clause can be added to execute another piece of code when the condition is false. The else-clause is introduced by the else keyword followed by braces that contain the code that should be executed.

let a = 0
var b = 0

if a == 1 {
   b = 1
} else {
   b = 2
}

// `b` is `2`

The else-clause can contain another if-statement, i.e., if-statements can be chained together. In this case the braces can be omitted.

let a = 0
var b = 0

if a == 1 {
   b = 1
} else if a == 2 {
   b = 2
} else {
   b = 3
}

// `b` is `3`

if a == 1 {
   b = 1
} else {
    if a == 0 {
        b = 2
    }
}

// `b` is `2`

Last updated