Else
Do one thing when true, another when false.
1let isRaining = false
2if isRaining {
3 print("Take an umbrella!")
4} else {
5 print("Enjoy the sunshine!")
6}
$ swift main.swift
Enjoy the sunshine!
Every line, explained
let isRaining = false- 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 isRaining {- if checks a condition. Swift style: no round brackets around the condition, but the curly braces { } are always required. The condition is just the constant isRaining, which is false, so this block is skipped.
print("Take an umbrella!")- 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 condition above is false.
} 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.
print("Enjoy the sunshine!")- 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 is the line that runs.
}- This } closes the else block.