Else If
Check several conditions, one after another.
1let number = 2
2if number == 1 {
3 print("one")
4} else if number == 2 {
5 print("two")
6} else {
7 print("something else")
8}
$ swift main.swift
two
Every line, explained
let number = 2- let creates a constant: a named box whose value is set once and can never change. Swift people reach for let by default: if a value never needs to change, locking it down prevents accidents.
if number == 1 {- if checks a condition. Swift style: no round brackets around the condition, but the curly braces { } are always required. == asks "are these equal?". Careful: a single = stores a value, a double == compares. 2 == 1 is false, so this block is skipped.
print("one")- print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them. Skipped: number is not 1.
} else if number == 2 {- } else if ... { adds another check that is only tried when the one above was false. Swift tests each condition top to bottom and runs the first block whose condition is true. 2 == 2 is true, so this block runs.
print("two")- print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them. This line runs.
} else {- } else { attaches an "otherwise" branch. When the if condition is false, the code inside the else block runs instead. Exactly one of the two blocks runs, never both. Only runs when every check above it failed.
print("something else")- print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them. Skipped: the else if above already matched.
}- This } closes the else block.