Programs make decisions all the time: show a warning when the battery is low, greet the user differently in the evening, give a grade based on a score, choose an icon for the weather. Swift makes these decisions with if and switch.
Swift's switch is far more capable than in many older languages. Cases can match several values, ranges of numbers, tuples and patterns, and a switch must be exhaustive, handling every possible value, so cases can't be forgotten by accident. There's also no accidental "fall through" from one case into the next.
In this lesson you'll write if chains and the compact ternary operator, then use switch with values, ranges, tuples and extra conditions, and finally use if and switch as expressions that produce a value directly.
if, else if and else
let temperature = 18
if temperature > 25 {
print("Shorts weather")
} else if temperature > 15 {
print("Bring a jumper")
} else {
print("Coat on")
}- No brackets are needed around the condition, but the braces are required, even for one line.
- The condition must be a real
Bool; Swift won't treat a number as true or false. - Only the first true branch runs.
The ternary operator picks between two values in one line: let label = score >= 50 ? "Pass" : "Fail". Keep it for simple choices; nested ternaries are hard to read.
switch basics
switch day {
case "Sat", "Sun":
print("Weekend")
case "Fri":
print("Almost there")
default:
print("Weekday")
}- Each
caselists one or more values, separated by commas. - A switch must be exhaustive. For strings and numbers, that means a
defaultcase. For enums, listing every case is enough. - There's no fallthrough: after a matching case runs, the switch ends. No
breakis needed. - Every case must contain at least one statement; write
breakfor a case that should do nothing.
Ranges, tuples and where
Cases can match much more than single values:
switch score {
case 90...100: grade = "A"
case 75..<90: grade = "B"
case 0..<75: grade = "C"
default: grade = "Invalid"
}
switch (x, y) {
case (0, 0): print("Origin")
case (_, 0): print("On the x-axis")
case (let a, let b) where a == b: print("On the diagonal")
default: print("Somewhere else")
}_ matches anything, let binds part of the value to a name, and where adds an extra condition to a case.
if and switch expressions
Since Swift 5.9, if and switch can produce a value directly when each branch is a single expression:
let fee = if isMember { 0.0 } else { 4.99 }
let advice = switch weather {
case "sun": "Sun cream"
case "rain": "Umbrella"
default: "Check the forecast"
}This avoids declaring a variable and assigning it in every branch. On older Swift versions, use the ternary operator or assign inside each branch.
fallthrough and if case
Swift's switch never falls into the next case by accident, but you can ask for it with fallthrough. It runs the next case's body without checking that case's pattern:
let code = 404
switch code {
case 200..<300:
print("Success")
case 404:
print("Not found")
fallthrough
case 400..<500:
print("Client error")
default:
print("Other")
}
// Not found
// Client errorYou'll rarely need it; listing several values in one case is usually clearer.
When you only care about one pattern, a whole switch is heavy. if case tests a single pattern, using the same syntax as a case:
let rating = 4
if case 1...5 = rating { print("Valid rating") }
let point = (2, 0)
if case (_, 0) = point { print("On the x-axis") }The pattern comes first and the value after =. It reads backwards at first, but it lets you use ranges, tuples and enum cases in an ordinary if.
Several conditions separated by commas
An if can take a list of conditions separated by commas. They're checked left to right, and the block runs only if every one is true, much like &&:
if age >= 18, hasTicket, seat != nil {
print("Come in")
}The difference shows up with optionals: a comma list can mix let unwrapping with ordinary tests, as in if let seat, seat > 10, where && can't. The same rule applies to guard and while.
Swift Conditions Syntax
Conditions
if cond { } else if other { } else { }
let x = cond ? a : b
switch value {
case 1, 2: ...
case 3...9: ...
case let n where n > 100: ...
default: ...
}
let y = if cond { a } else { b } // Swift 5.9+Swift Conditions Summary
- if, else if and else run the first branch whose condition is true; braces are required.
- The ternary
c ? a : bchooses between two values. - switch must be exhaustive and never falls through; no break is needed.
- Cases can match several values, ranges, tuples, bound values with let, and extra where conditions.
- In Swift 5.9+, if and switch can be used as expressions.
Swift Conditions Examples
Each example shows the code, the output it produces and what each part does.
Grades with switch and ranges
func grade(for score: Int) -> String {
switch score {
case 90...100: return "A"
case 75..<90: return "B"
case 50..<75: return "C"
case 0..<50: return "Fail"
default: return "Invalid score"
}
}
for s in [95, 80, 50, 12, 140] {
print("\(s): \(grade(for: s))")
}95: A
80: B
50: C
12: Fail
140: Invalid scoreLine-by-line explanation
- Line 390...100 includes both ends.
- Line 475..<90 includes 75 but not 90.
- Line 7default handles everything outside 0 to 100.
if, else and the ternary operator
let basket = 62.0
let isMember = false
let delivery = basket >= 50 ? 0.0 : 4.99
var discount = 0.0
if isMember {
discount = basket * 0.1
} else if basket > 100 {
discount = 5
}
print("Delivery: \(delivery), discount: \(discount)")
print("Total: \(basket + delivery - discount)")Delivery: 0.0, discount: 0.0
Total: 62.0Line-by-line explanation
- Line 4The ternary picks the delivery charge in one line.
- Lines 6 to 10Neither condition is true, so discount stays at 0.0.
- Line 12Doubles print with .0 even when they're whole numbers.
Tuples, binding and where
let points = [(0, 0), (3, 0), (2, 2), (1, 5)]
for point in points {
switch point {
case (0, 0):
print("\(point) is the origin")
case (_, 0):
print("\(point) is on the x-axis")
case let (x, y) where x == y:
print("\(point) is on the diagonal")
case let (x, y):
print("\(point): x is \(x), y is \(y)")
}
}(0, 0) is the origin
(3, 0) is on the x-axis
(2, 2) is on the diagonal
(1, 5): x is 1, y is 5Line-by-line explanation
- Line 7_ matches any x value.
- Line 9let binds both parts, and where adds a condition.
- Line 11A final case that binds everything matches all remaining tuples, so no default is needed.
Common Swift Conditions Mistakes
Missing braces
if score > 50 print("Pass") // error: expected '{' after 'if' conditionif score > 50 { print("Pass") }A switch that isn't exhaustive
switch day {
case "Sat", "Sun": print("Weekend")
} // error: switch must be exhaustiveswitch day {
case "Sat", "Sun": print("Weekend")
default: print("Weekday")
}Using a number as a condition
let count = 3
if count { print("Has items") } // error: 'Int' is not convertible to 'Bool'if count > 0 { print("Has items") }Swift Conditions in Real Projects
Conditions in apps
SwiftUI views use if to show or hide parts of a screen, such as an error message or an empty-state illustration, and switch to pick the right view for each state of a loading process. Because switches over enums must be exhaustive, adding a new state forces every screen that displays it to be updated, which prevents blank or broken screens.
Swift Conditions FAQ
When should I use switch instead of if-else in Swift?
Use switch when you're comparing one value against several possibilities, especially enum cases, ranges or tuples. The compiler checks that every case is covered, which if-else chains can't do. For one or two unrelated conditions, if is simpler.
Does Swift switch fall through like C or Java?
No. Only the matching case runs, then the switch ends, so you never need break to stop it. If you really want to continue into the next case, write fallthrough at the end of the case.
Can I use a switch on a string in Swift?
Yes. switch works with strings, numbers, characters, tuples, enums and any type that supports pattern matching. Because strings have endless possible values, you must include a default case.
How do I write a one-line if else in Swift?
Use the ternary operator, condition ? valueIfTrue : valueIfFalse, for example let label = isOn ? "On" : "Off". From Swift 5.9 you can also write let label = if isOn { "On" } else { "Off" }.
Why does Swift say "Switch must be exhaustive"?
Every possible value must match some case. For an Int or String, that means adding a default case; for an enum, list every case or add default. The check stops values from slipping through a switch unhandled.
Swift Conditions Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the ternary so label is "Even" or "Odd".
let label = n % 2 == 0 "Even" : "Odd"
What does this print?
let x = 7
switch x {
case 1, 3, 5, 7, 9: print("odd")
default: print("even")
}
What does this print?
let t = 18
if t > 25 { print("hot") } else if t > 15 { print("mild") } else if t > 5 { print("cool") }
Which case matches every number from 10 up to, but not including, 20?
What does case let (x, y) where x > y: do?
Swift Conditions Quiz
5 questions to check what you learned.
Does a Swift switch case fall through to the next case?
- Yes, unless you write break
- Only for strings
- Only with default
- No, never by default
Why does a switch over a String need default?
- A switch must be exhaustive, and there are endless possible strings
- Strings are special
- default is always required
- To add a break
What does
_match in a switch case?- Nothing
- Any value
- Only zero
- Only nil
Are braces optional for a one-line if in Swift?
- No, they're always required
- Yes
- Only with else
- Only in playgrounds
What does
let fee = if isMember { 0.0 } else { 4.99 }require?- Nothing, it works in every version
- A ternary operator
- A switch
- Swift 5.9 or later, where if can be an expression