Swift Conditional Statements
A conditional statement tells your program to take a specific action when a certain condition is true. Without conditionals, every program would do the same thing every time — with them, programs can make decisions.
The Traffic Light Analogy
┌─────────────────────────────────────────────┐
│ Traffic Light Decision │
│ │
│ IF light is Green → Drive │
│ ELSE IF light is Yellow → Slow down │
│ ELSE (light is Red) → Stop │
│ │
│ Your code works exactly the same way. │
└─────────────────────────────────────────────┘
The if Statement
let temperature = 38
if temperature > 35 {
print("It is very hot today.")
}
Swift checks whether temperature > 35 is true. Since 38 is greater than 35, the message prints. If the condition were false, the block would be skipped entirely.
The if-else Statement
let score = 45
if score >= 50 {
print("You passed.")
} else {
print("You need to improve.")
}
When the condition is false, the else block runs. Exactly one of the two blocks always executes.
The if-else if-else Chain
let marks = 72
if marks >= 90 {
print("Grade: A")
} else if marks >= 75 {
print("Grade: B")
} else if marks >= 60 {
print("Grade: C")
} else {
print("Grade: F")
}
// Output: Grade: C
Swift checks each condition from top to bottom. As soon as one condition is true, it runs that block and skips the rest.
Nested if Statements
let hasID = true
let age = 20
if hasID {
if age >= 18 {
print("Entry allowed.")
} else {
print("Too young to enter.")
}
} else {
print("ID required.")
}
An if can live inside another if. This handles situations where multiple conditions build on each other.
Combining Conditions
let username = "admin"
let password = "secure123"
if username == "admin" && password == "secure123" {
print("Login successful.")
} else {
print("Invalid credentials.")
}
Both conditions must be true for the login to succeed. The && operator requires all parts to pass.
Guard Statement – Early Exit
func processAge(_ age: Int) {
guard age >= 0 else {
print("Invalid age.")
return
}
print("Age is valid: \(age)")
}
processAge(25) // Age is valid: 25
processAge(-5) // Invalid age.
Why Guard Exists
┌──────────────────────────────────────────────┐
│ Without guard: With guard: │
│ │
│ if valid { guard valid else { │
│ do work return │
│ more work } │
│ more... do work ← less nesting │
│ } more work │
│ more... │
│ │
│ Guard keeps the main logic at top level. │
└──────────────────────────────────────────────┘
A guard statement checks a condition and exits early if it fails. It keeps your main logic clean by removing invalid cases upfront.
