Line At A Time
Lesson 12: The AND Operator
The AND Operator Combine conditions with &&.
1let hungry = true
2let haveSnacks = false
3if hungry && haveSnacks {
4 print("Snack time!")
5} else {
6 print("No snacks right now")
7}
Terminal
$ swift main.swift
No snacks right now
Every line, explained
let hungry = true
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.
let haveSnacks = 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 hungry && haveSnacks {
if checks a condition. Swift style: no round brackets around the condition, but the curly braces { } are always required. && means AND: the condition is only true if BOTH sides are true. true && false is false, so this block is skipped.
print("Snack time!")
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: we have no snacks.
} 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("No snacks right now")
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.