Swift Short-Hand if…else

🍎 Swift Short-Hand if…else
In Swift Short-Hand if…else means writing decision logic in fewer lines while keeping the code clean, readable, and safe.
This is very common in real iOS apps and frequently asked in interviews.
1️⃣ What is Swift Short-Hand if…else?
Short-hand if…else is used when:
The condition is simple
You want to assign a value based on a condition
You want clean & concise code
2️⃣ Ternary Conditional Operator ?: ⭐ (Most Common)
Syntax
Example
✔ Short
✔ Clean
✔ Interview favorite
3️⃣ Comparison with Normal if…else
Normal
Short-Hand
📌 Same logic, fewer lines
4️⃣ Short-Hand if…else with Numbers ⭐
5️⃣ Short-Hand with Boolean Values ⭐
6️⃣ Short-Hand with Function Calls ⭐⭐
7️⃣ Short-Hand with Optionals ⭐⭐
✅ Better & safer:
📌 Prefer nil-coalescing (??) for optionals
8️⃣ Short-Hand if as an Expression (Modern Swift ⭐⭐)
Swift allows if…else to return a value without ternary.
✔ Readable
✔ Powerful
✔ New Swift feature
9️⃣ When NOT to Use Short-Hand ❌
❌ Complex logic
❌ Multiple conditions
❌ Reduced readability
🔍 Ternary vs if…else (Interview)
| Feature | Ternary | if…else |
|---|---|---|
| Lines | 1 | Multiple |
| Readability | Medium | High |
| Complexity | Low | Any |
| Interview use | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
📌 Interview Questions & MCQs
Q1. Syntax of ternary operator?
A) if ? else :
B) condition ? true : false
C) ? :
D) if : else
✅ Answer: B
Q2. Best replacement for optional ternary?
A) if let
B) ?:
C) ??
D) switch
✅ Answer: C
Q3. Can ternary return values?
A) Yes
B) No
✅ Answer: A
Q4. Is ternary good for complex logic?
A) Yes
B) No
✅ Answer: B
🔥 Real-Life Use Cases
✔ UI labels
✔ Button titles
✔ Login states
✔ Validation messages
✔ Default values
✅ Summary
Short-hand
if…else= ternary operatorSyntax:
condition ? trueValue : falseValueClean & concise
Use
??for optionalsAvoid for complex logic
Important for Swift interviews & real apps
