Swift If…Else

🍎 Swift If…Else – Complete Tutorial

In Swift If…Else statements are used to make decisions based on conditions.
They control the flow of execution in iOS/macOS apps and are one of the most asked interview topics.


1️⃣ What is if…else in Swift?

An if…else statement:

  • Evaluates a Boolean condition

  • Executes code only if the condition is true

  • Optionally executes alternative code if false



2️⃣ Simple if Statement ⭐


 

✔ Executes only when condition is true


3️⃣ if…else Statement ⭐


 


4️⃣ if…else if…else Ladder ⭐

Used when multiple conditions are checked.


 


5️⃣ Conditions Must Be Boolean ⭐ (Very Important)

❌ Invalid (C/Java style):

// if age { ❌ }

✅ Valid:


📌 Swift does not auto-convert numbers to Booleans.


6️⃣ Using Logical Operators (&&, ||, !) ⭐


 


7️⃣ if with Optional Binding ⭐⭐

Safely unwrap optional values.


 

📌 Very common in real iOS apps


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

Swift allows if to return a value.


 

✔ Cleaner code
✔ Interview bonus


9️⃣ Nested if Statements ❌ (Avoid When Possible)


Better:



🔟 if vs switch ⭐ (Interview)

Feature if…else switch
Multiple conditions
Range matching
Cleaner for many cases
Simple checks

1️⃣1️⃣ Common Mistakes ❌

❌ Using non-Boolean condition
❌ Forgetting braces {}
❌ Deep nesting
❌ Ignoring optional safety


📌 Interview Questions & MCQs

Q1. Condition inside if must return?

A) Int
B) String
C) Boolean
D) Any

Answer: C


Q2. Which operator means AND?

A) &
B) &&
C) ||
D) !

Answer: B


Q3. How to safely unwrap optional?

A) unwrap()
B) if let
C) try
D) guard

Answer: B


Q4. Can if return a value in Swift?

A) No
B) Yes

Answer: B


Q5. Better alternative to long if-else chains?

A) Loop
B) Array
C) switch
D) Function

Answer: C


🔥 Real-Life Use Cases

✔ Form validation
✔ Login logic
✔ API response handling
✔ Access control
✔ UI state decisions


✅ Summary

  • if…else controls decision making

  • Conditions must be Boolean

  • Supports logical operators

  • Works with optionals (if let)

  • Can be used as an expression

  • Essential for Swift & iOS interviews

You may also like...