Swift else Statement
🍎 Swift else Statement – Simple & Clear Guide
In Swift else Statement works with if to execute code when the if condition is false.
It helps you handle both outcomes of a decision.
1️⃣ What is else in Swift?
-
elseruns only when theifcondition is false -
It must come after an
ifblock
Syntax
2️⃣ Basic if–else Example ⭐
✔ Output:
3️⃣ else if for Multiple Conditions ⭐
Used when you need to check more than one condition.
4️⃣ else with Logical Operators ⭐
5️⃣ else with Optional Binding ⭐⭐
Handle nil safely.
✔ Prevents crashes
✔ Common in real iOS apps
6️⃣ if–else as an Expression (Modern Swift ⭐⭐)
Swift allows if–else to return a value.
✔ Cleaner code
✔ Interview bonus point
7️⃣ Nested else ❌ (Avoid When Possible)
✅ Better:
8️⃣ Common Mistakes ❌
❌ Using else without if
❌ Forgetting {}
❌ Deep nesting
❌ Using non-Boolean conditions
📌 Interview Questions & Quick Answers
Q1. When does else execute?
👉 When if condition is false
Q2. Can else exist without if?
👉 ❌ No
Q3. Can if–else return a value in Swift?
👉 ✅ Yes
Q4. What is better for many conditions: else if or switch?
👉 switch
✅ Summary
-
elsehandles the false condition -
Always paired with
if -
Use
else iffor multiple checks -
Works with optionals and expressions
-
Core topic for Swift fundamentals & interviews
