Swift Conditionals
Conditionals let your code make decisions. Think of them as traffic lights in a program: they check a situation and direct the flow of execution down one path or another.
The if Statement
The simplest conditional runs a block of code only when a condition is true.
let temperature = 35
if temperature > 30 {
print("It's hot outside.")
}
// Output: It's hot outside.If the condition inside the parentheses is false, the block is skipped entirely.
if-else
Add an else block to handle the false case.
let speed = 80
if speed > 100 {
print("Speeding!")
} else {
print("Speed is fine.")
}
// Output: Speed is fine.if-else if-else Chain
Use else if to check multiple conditions in sequence. Swift checks each one top to bottom and stops at the first true condition.
let score = 75
if score >= 90 {
print("Grade: A")
} else if score >= 80 {
print("Grade: B")
} else if score >= 70 {
print("Grade: C")
} else {
print("Grade: F")
}
// Output: Grade: CDiagram: if-else if Flow
score = 75
|
score >= 90?
No |
score >= 80?
No |
score >= 70?
Yes |
v
print("Grade: C")
The switch Statement
A switch statement compares a single value against multiple cases. It is cleaner than a long chain of else if blocks when checking exact values.
let day = "Monday"
switch day {
case "Saturday", "Sunday":
print("Weekend")
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
print("Weekday")
default:
print("Unknown day")
}
// Output: WeekdayNo Fallthrough by Default
In Swift, matching one case does not automatically run the next case. Each case is independent. This is different from C and Java, where you need explicit break statements.
switch With Ranges
let age = 17
switch age {
case 0...12:
print("Child")
case 13...17:
print("Teenager")
case 18...64:
print("Adult")
default:
print("Senior")
}
// Output: Teenagerswitch With Tuples
A tuple groups multiple values together. You can match on all of them at once.
let point = (2, 0)
switch point {
case (0, 0):
print("Origin")
case (let x, 0):
print("On x-axis at \(x)")
case (0, let y):
print("On y-axis at \(y)")
default:
print("Somewhere else")
}
// Output: On x-axis at 2Guard Statement
A guard statement checks a condition and exits early if it fails. It keeps your main logic at the left margin and avoids deeply nested code.
func checkAge(age: Int) {
guard age >= 18 else {
print("Must be 18 or older.")
return
}
print("Access granted.")
}
checkAge(age: 16) // Must be 18 or older.
checkAge(age: 22) // Access granted.Diagram: guard vs if
Without guard (nested): With guard (flat):
if isValid { guard isValid else { return }
if hasPermission { guard hasPermission else { return }
if isAvailable { guard isAvailable else { return }
doWork() doWork()
}
}
}
The guard version is flatter and easier to follow. Each requirement sits at the same level.
Conditional Binding with if let
Swift optionals (values that might be missing) work well with conditional binding. You will study optionals in depth in a later topic, but here is a quick preview.
let userInput: String? = "Alice"
if let name = userInput {
print("Hello, \(name)")
} else {
print("No name provided.")
}
// Output: Hello, AliceSummary
Swift conditionals include if, if-else, else if chains, switch, and guard. Use switch for clean multi-case matching, and use guard to exit early when requirements are not met. Each tool keeps your logic readable and your code safe.
