← Swift tutorial

Swift

Conditionals

if/else if/else work as usual — no parentheses needed around the condition, unlike most other C-family languages in this tutorial.

Example: a time-of-day greeting

let hour = 14
let greeting: String

if hour < 12 {
    greeting = "Good morning"
} else if hour < 18 {
    greeting = "Good afternoon"
} else {
    greeting = "Good evening"
}

print(greeting)
Good afternoon

Swift's switch is also commonly used for multi-way branches, and unlike some languages, it doesn't silently fall through to the next case by default — each case is self-contained, which avoids a classic C/Java bug where a forgotten break lets execution accidentally continue into the next case.

Example
let hour = 14
let greeting: String

if hour < 12 {
    greeting = "Good morning"
} else if hour < 18 {
    greeting = "Good afternoon"
} else {
    greeting = "Good evening"
}

print(greeting)
Output
Good afternoon