Coding for All
Lesson 8: If Statements
If Statements Only run code when a condition is true.
1let age = 10
2if age > 8 {
3 print("You are older than 8")
4}
Terminal
$ swift main.swift
You are older than 8
Every line, explained
let age = 10
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 age > 8 {
if checks a condition. Swift style: no round brackets around the condition, but the curly braces { } are always required. Here > means "greater than", and 10 > 8 is true, so the code inside runs.
print("You are older than 8")
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 } closes the if block.