← Back to Swift Course | Chapter 3: Control Flow | Lesson 1 of 8

If-Else Statements

An if-else statement lets your program make a decision, like choosing one path if something is true and another path if it's not.

Basic if Statement

An if statement runs its block of code only when the condition inside the parentheses-free header evaluates to true.

Example: Basic if Statement

markup
let temperature = 30
if temperature > 25 {
    print("It is hot outside")
}

if-else

Adding an else clause provides a fallback block that runs when the if condition is false.

Example: if-else

markup
let temperature = 15
if temperature > 25 {
    print("It is hot outside")
} else {
    print("It is not that hot")
}

else if Chains

Multiple conditions can be checked in order using else if, stopping at the first one that is true.

Note: Swift requires curly braces around every branch body, even a single-line one.

Example: else if Chains

markup
let score = 72
if score >= 90 {
    print("Grade: A")
} else if score >= 70 {
    print("Grade: B")
} else {
    print("Grade: C or below")
}
Common Mistakes
  1. Wrapping the condition in parentheses like if (x > 5), which is unnecessary and not idiomatic Swift (though harmless).
  2. Forgetting the curly braces around a single-statement body; Swift requires them, unlike some C-style languages.
  3. Chaining many separate if statements when a single else if chain (or switch) would be clearer.
Chapter Summary
  • if executes a block only when its condition is true.
  • else if checks additional conditions in sequence, and else runs when none matched.
  • Curly braces { } are mandatory in Swift, even for a single statement.
  • Conditions must be actual Bool expressions -- Swift will not accept an Int as a condition.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.