100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Swift

if-else Statements in Swift

Learn how Swift's if-else statement branches execution using strictly typed Bool conditions and mandatory braces.

Control FlowBeginner6 min readJul 8, 2026
Analogies

Introduction

The if-else statement is the most basic form of conditional branching in Swift. It lets a program execute one block of code when a condition is true and another block when it is false. Unlike C, Objective-C, or JavaScript, Swift requires the condition inside an if statement to be a genuine Bool value — there is no automatic conversion from integers or other types to true/false. This design choice removes an entire class of bugs caused by accidentally writing if (x = 1) or relying on nonzero numbers being 'truthy'.

🏏

Cricket analogy: Unlike some scoring apps that treat any nonzero run count as 'out,' Swift's if statement requires a genuine Bool like 'isOut,' never auto-converting a run total, preventing bugs from misreading a score as a dismissal.

Syntax

swift
if condition {
    // executed when condition is true
} else if anotherCondition {
    // executed when anotherCondition is true
} else {
    // executed when all conditions are false
}

Explanation

Parentheses around the condition are optional and idiomatic Swift omits them, but the curly braces around each branch are always mandatory, even for a single statement. The condition and anotherCondition expressions must evaluate to a Bool — writing if x where x is an Int is a compile-time error. You can chain as many else if clauses as needed, and the final else is optional; if omitted and no condition matches, control simply falls through to the code after the statement.

🏏

Cricket analogy: Just as an umpire's signal for six must be a full raised-arms gesture, no shortcuts, Swift's curly braces around each if branch are mandatory even for one line, while parentheses around 'isSix' are optional; you can chain else-if for four, out, or wide.

Example

swift
let temperature = 28

if temperature > 30 {
    print("It's hot outside.")
} else if temperature > 20 {
    print("It's warm outside.")
} else {
    print("It's cold outside.")
}

Output

swift
It's warm outside.

Key Takeaways

  • The condition in an if statement must be a Bool — Swift has no implicit truthy/falsy conversion.
  • Parentheses around the condition are optional; curly braces around each branch are mandatory.
  • else if chains let you test multiple conditions in order, top to bottom.
  • The trailing else clause is optional and runs only if no prior condition matched.
  • if can also be used as an expression in Swift 5.9+ to directly produce a value.

Practice what you learned

Was this page helpful?

Topics covered

#Swift#SwiftProgrammingStudyNotes#Programming#IfElseStatementsInSwift#Else#Statements#Syntax#Explanation#StudyNotes#SkillVeris