Swift if Statement

🍎 Swift if Statement – Simple & Clear Guide

In Swift, the if statement is used to execute code only when a condition is true.
It’s the foundation of decision-making in Swift and iOS development.


1️⃣ What is if in Swift?

The if statement:

  • Checks a Boolean condition

  • Runs code only if the condition evaluates to true

Syntax



2️⃣ Basic if Example ⭐


 

Output:

Eligible to vote

3️⃣ Condition Must Be Boolean ⭐ (Very Important)

Swift does NOT allow non-Boolean conditions.

❌ Invalid:

// if age { ❌ }

✅ Valid:



4️⃣ Using Comparison Operators with if


 

Common operators:

  • == equal

  • != not equal

  • > greater than

  • < less than

  • >=, <=


5️⃣ Using Logical Operators with if


 

Logical operators:

  • && → AND

  • || → OR

  • ! → NOT


6️⃣ if with Optional Binding ⭐⭐

Safely unwrap optional values.


 

✔ Prevents crashes
✔ Very common in iOS apps


7️⃣ Multiple Conditions in One if


 


8️⃣ if as an Expression (Modern Swift ⭐⭐)

Swift allows if to return a value.


 

✔ Cleaner
✔ Interview bonus


9️⃣ Common Mistakes ❌

❌ Using non-Boolean condition
❌ Forgetting {}
❌ Deep nesting instead of logical operators
❌ Ignoring optional safety


📌 Interview Questions & Quick Answers

Q1. What type must an if condition return?
👉 Bool

Q2. Does Swift allow if (x) like C?
👉 ❌ No

Q3. How to safely unwrap optionals in if?
👉 if let

Q4. Can if return a value in Swift?
👉 ✅ Yes


✅ Summary

  • if executes code when condition is true

  • Condition must be Boolean

  • Supports comparison & logical operators

  • Works with optionals using if let

  • Can be used as an expression

  • Core topic for Swift & iOS interviews

You may also like...