Conditionals and Switch
if/else as expected, plus Swift's switch statement — far more powerful than a simple multi-way branch.
読了時間 2 分
if/else in Swift looks like most other languages, but Swift's switch statement goes well beyond a simple multi-way branch — it's one of the language's most powerful control-flow tools, built around pattern matching.
if / else if / else
let temperature = 15
if temperature > 25 {
print("Hot")
} else if temperature > 10 {
print("Mild")
} else {
print("Cold")
}Unlike some languages, Swift doesn't require (or allow) parentheses around the condition, but the braces { } are always required — even for a single statement — which prevents an entire category of bugs where a missing brace silently changes which line an if controls.
switch: exhaustive by default
A Swift switch must cover every possible case — there's no accidental fallthrough to a case you didn't intend, and the compiler forces you to be exhaustive:
let grade = "B"
switch grade {
case "A":
print("Excellent")
case "B", "C":
print("Good")
default:
print("Needs improvement")
}Multiple values can share one case ("B", "C"), and default catches anything not explicitly listed. If you switch over an enum (covered later in this course) and handle every case, you don't even need default — the compiler already knows nothing is left uncovered.
Matching ranges and patterns
switch can match against ranges, not just exact values:
let score = 82
switch score {
case 90...100:
print("A")
case 80..<90:
print("B")
case 70..<80:
print("C")
default:
print("F")
}Binding values inside a case
A case can pull values out of what it matches, using let right inside the pattern:
let point = (x: 3, y: -2)
switch point {
case (0, 0):
print("Origin")
case (let x, 0):
print("On the x-axis at \(x)")
case (0, let y):
print("On the y-axis at \(y)")
case (let x, let y):
print("At (\(x), \(y))")
}where clauses add a condition to a case
let number = 12
switch number {
case let n where n % 2 == 0:
print("\(n) is even")
default:
print("\(number) is odd")
}This combination — matching a shape and binding values and adding an extra condition — is why Swift developers reach for switch far more often than in other languages. Once you're used to it, a long if/else if chain checking related conditions starts to look like a switch that hasn't been written yet.