Swift If Else: Conditions, Syntax, and Practical Examples
Swift uses if, else if, and else to run different code depending on whether a condition is true or false. This is one of the most important control flow tools in Swift, because it lets your programs make decisions based on user input, data values, and application state.
Quick answer: In Swift, an if statement checks a Boolean condition. If the condition is true, that block runs; if it is false, Swift can run an else block or test another condition with else if.
Difficulty: Beginner
Helpful to know first: You'll understand this better if you know basic Swift syntax, how variables store values, and simple types like Int, String, and Bool.
1. What Is If & Else?
An if statement is a conditional branch. It asks a yes-or-no question using a Boolean expression and then decides which code should run.
- if runs code only when a condition is true.
- else runs code when the if condition is false.
- else if lets you test additional conditions in order.
- Swift requires each condition to evaluate to a real Bool.
- This is different from some languages that allow numbers or strings as conditions.
For example, a program might check whether a score is passing, whether a username is empty, or whether an age is high enough for a feature. Without conditional logic, programs would always behave the same way regardless of input.
A common beginner confusion is expecting Swift to treat values like 1 or a non-empty string as true automatically. Swift does not do that. The condition must already be Boolean, such as age >= 18 or isLoggedIn.
2. Why If & Else Matters
Almost every real Swift program depends on decision-making. Even simple command-line programs need to compare values and choose between outcomes.
You use if and else when you need to:
- validate user input before processing it
- show different messages for different cases
- guard against invalid values
- choose one calculation path over another
- respond differently to app state, permissions, or settings
You should not use long chains of if statements when the logic is better represented by another tool, such as switch for many fixed matching cases. But for everyday true-or-false decisions, if is usually the clearest choice.
3. Basic Syntax or Core Idea
The basic form of an if statement in Swift is very direct. You write a Boolean condition after if, then place the code to run inside braces.
Simple if statement
This example runs a line only when the condition is true.
let age = 20
if age >= 18 {
print("You are an adult.")
}
Here, age >= 18 produces a Boolean result. Because it is true, the print statement runs.
If with else
Use else when you want one path for true and another path for false.
let isRaining = true
if isRaining {
print("Take an umbrella.")
} else {
print("Enjoy the weather.")
}
Because isRaining is already a Boolean, it can be used directly as the condition.
If with else if
Use else if when you need to test more than two possibilities.
let temperature = 12
if temperature >= 25 {
print("It's warm.")
} else if temperature >= 15 {
print("It's mild.")
} else {
print("It's cool.")
}
Swift checks these conditions from top to bottom and stops at the first true one.
Operators commonly used in conditions
Conditions often use comparison and logical operators.
let score = 85
let hasBonus = true
if score >= 80 && hasBonus {
print("Excellent result.")
}
In this code, >= compares values and && requires both conditions to be true.
4. Step-by-Step Examples
Example 1: Checking if a number is positive
This example uses a simple true-or-false check.
let number = 7
if number > 0 {
print("The number is positive.")
}
Because 7 > 0 is true, the message is printed.
Example 2: Choosing between two messages
This version uses else so one branch always runs.
let username = "Taylor"
if username == "" {
print("Please enter a username.")
} else {
print("Welcome, \(username)!")
}
If the string is empty, the program asks for input. Otherwise, it prints a welcome message.
Example 3: Grading with else if
Multiple ranges are a common reason to use else if.
let grade = 76
if grade >= 90 {
print("A")
} else if grade >= 80 {
print("B")
} else if grade >= 70 {
print("C")
} else {
print("Needs improvement")
}
Swift checks from top to bottom. Since 76 >= 70 is the first true condition, it prints C.
Example 4: Combining conditions
You can combine multiple Boolean expressions to create more specific rules.
let age = 22
let hasTicket = true
if age >= 18 && hasTicket {
print("Entry allowed.")
} else {
print("Entry denied.")
}
This is useful when more than one rule must be satisfied at the same time.
5. Practical Use Cases
- Checking whether a user is old enough to access a feature.
- Displaying different text when a form field is empty or filled in.
- Validating a password length before allowing account creation.
- Choosing a shipping fee based on order total.
- Handling game logic such as win, lose, or bonus states.
- Deciding whether to retry a task based on a success flag.
- Showing different output based on numeric ranges like scores, prices, or temperatures.
6. Common Mistakes
Mistake 1: Using a non-Boolean value as the condition
In Swift, the condition inside an if statement must evaluate to true or false. A number or string cannot be used directly as a condition.
Problem: This code uses an Int where Swift expects a Bool, so it will not compile.
let count = 3
if count {
print("There are items.")
}
Fix: Write a comparison that produces a Boolean value.
let count = 3
if count > 0 {
print("There are items.")
}
The corrected version works because count > 0 evaluates to a Boolean.
Mistake 2: Writing assignment instead of comparison
Beginners sometimes try to compare values using = instead of ==. In Swift, = assigns a value, while == checks equality.
Problem: This condition attempts assignment where a Boolean comparison is required, so the code is invalid.
var isMember = true
if isMember = true {
print("Discount applied.")
}
Fix: Compare with ==, or use the Boolean variable directly when possible.
let isMember = true
if isMember {
print("Discount applied.")
}
The corrected version works because the condition is a proper Boolean expression.
Mistake 3: Ordering else if conditions incorrectly
When conditions overlap, order matters. Swift stops at the first true branch, so a broad condition placed first can hide a more specific one below it.
Problem: This code checks the lower threshold first, so the higher-score branch never runs for values above 90.
let score = 95
if score >= 70 {
print("Passed")
} else if score >= 90 {
print("Excellent")
}
Fix: Put the most specific or highest-priority condition first.
let score = 95
if score >= 90 {
print("Excellent")
} else if score >= 70 {
print("Passed")
}
The corrected version works because Swift reaches the more specific match before the broader one.
Mistake 4: Comparing a Boolean to true or false unnecessarily
Swift allows direct use of Boolean values in conditions. Explicit comparisons to true or false are often longer and less readable.
Problem: This code is more verbose than necessary and can make simple conditions harder to read.
let isLoggedIn = false
if isLoggedIn == true {
print("Show dashboard.")
} else {
print("Show sign-in screen.")
}
Fix: Use the Boolean directly, or negate it with ! when needed.
let isLoggedIn = false
if isLoggedIn {
print("Show dashboard.")
} else {
print("Show sign-in screen.")
}
The corrected version works because the condition is shorter and clearer without changing the logic.
7. Best Practices
Use conditions that read like plain logic
Good conditional code should be easy to read without extra mental effort. Favor expressions that make the rule obvious.
Less clear:
let temperature = 30
if !(temperature < 25) {
print("Hot day")
}
Preferred:
let temperature = 30
if temperature >= 25 {
print("Hot day")
}
The preferred version communicates the rule directly.
Put special cases before general cases
When multiple branches overlap, place the most specific match first. This prevents broader conditions from catching values too early.
Less preferred:
let points = 100
if points >= 50 {
print("Reward unlocked")
} else if points == 100 {
print("Maximum reward unlocked")
}
Preferred:
let points = 100
if points == 100 {
print("Maximum reward unlocked")
} else if points >= 50 {
print("Reward unlocked")
}
The preferred version preserves the intended priority of the conditions.
Keep each branch focused
If branches become very long, the decision itself becomes harder to understand. Keep the condition simple and move complex work into functions when possible.
Less preferred:
let isPremium = true
if isPremium {
print("Load premium dashboard")
print("Load premium widgets")
print("Load premium reports")
}
Preferred:
func showPremiumExperience() {
print("Load premium dashboard")
print("Load premium widgets")
print("Load premium reports")
}
let isPremium = true
if isPremium {
showPremiumExperience()
}
The preferred version makes the decision logic easier to scan and reuse.
8. Limitations and Edge Cases
- Swift requires a Boolean condition. You cannot use integers, strings, or optionals as truthy or falsy shortcuts.
- Only the first matching branch in an if / else if chain runs.
- Long chains of conditions can become hard to maintain. In some cases, switch is clearer.
- Conditions are checked in order, so branch order can change program behavior.
- An else block is optional. If it is missing and the condition is false, no branch runs.
- Complex combined conditions with && and || can be difficult to read without parentheses.
- If your condition depends on an optional value, you often need optional binding such as if let rather than a plain comparison.
A common next-step comparison is plain if versus if let. Plain if checks a Boolean condition, while if let safely unwraps an optional only if it contains a value.
9. Practical Mini Project
This small program checks an order total and membership status to decide shipping and discount messages. It uses if, else if, and else in a realistic way.
let orderTotal = 72.5
let isMember = true
if orderTotal >= 100 {
print("You qualify for free express shipping.")
} else if orderTotal >= 50 {
print("You qualify for free standard shipping.")
} else {
print("Shipping charges apply.")
}
if isMember {
print("Member discount applied.")
} else {
print("Join to receive member discounts.")
}
This example shows two separate decisions. The first checks a numeric range for shipping, and the second checks a Boolean flag for membership benefits.
10. Key Points
- if runs code only when its condition is true.
- else provides a fallback path when the if condition is false.
- else if lets you test multiple conditions in sequence.
- Swift conditions must evaluate to Bool.
- Condition order matters because Swift stops at the first true branch.
- Comparison and logical operators are commonly used inside conditions.
- Readable conditions and clear branch order make code easier to maintain.
11. Practice Exercise
Build a small program that checks a person's age and prints the correct ticket category.
- If the age is less than 13, print Child ticket.
- If the age is from 13 through 64, print Standard ticket.
- If the age is 65 or older, print Senior ticket.
Expected output: For an age of 70, the program should print Senior ticket.
Hint: Start by checking the highest-priority or most specific range in a clear order.
let age = 70
if age < 13 {
print("Child ticket")
} else if age >= 65 {
print("Senior ticket")
} else {
print("Standard ticket")
}
12. Final Summary
Swift if, else if, and else statements are the foundation of decision-making in your code. They let you branch based on Boolean conditions, compare values, combine rules with logical operators, and choose the right behavior for each situation.
In this article, you saw the core syntax, worked through practical examples, learned how branch order affects results, and fixed common mistakes such as using non-Boolean conditions or writing comparisons incorrectly. Once you are comfortable with if and else, a useful next step is learning related Swift control flow tools such as switch, guard, and if let for optionals.