Swift for Loop

🔁 Swift for Loop – Complete Beginner to Interview Guide
In Swift, the for-in loop is used to run a block of code a set number of times. It can also go through collections like ranges, arrays, and strings.
1️⃣ What is for Loop in Swift? ⭐
Executes code for each value in a sequence
Best when number of iterations is known
Commonly used with ranges, arrays, dictionaries
2️⃣ Basic for-in Loop ⭐
Syntax
Example
Output
3️⃣ Closed Range vs Half-Open Range ⭐⭐
Closed Range (...)
Output:
Half-Open Range (..<)
Output:
4️⃣ Loop Without Using Variable ⭐⭐
Output
5️⃣ for Loop with Arrays ⭐⭐
Output
6️⃣ for Loop with Dictionary ⭐⭐⭐
Output (order may vary)
7️⃣ for Loop with String ⭐⭐
Output
8️⃣ Using stride() for Steps ⭐⭐⭐
Increment
Output:
Decrement
Output:
9️⃣ Using break and continue ⭐⭐
break
Output:
continue
Output:
🔟 Common Mistakes ❌
❌ Using C-style for loop (not allowed)
❌ Confusing ... and ..<
❌ Wrong stride direction
❌ Forgetting break condition
📌 Interview Questions
Q1. Does It support C-style for loop?
👉 ❌ No
Q2. What does ..< mean?
👉 Half-open range (excludes last value)
Q3. How to skip values in loop?
👉 Use stride()
✅ Summary
✔ It uses for-in loop
✔ Works with ranges & collections
✔ Supports step control via stride()
✔ break and continue control flow
✔ Essential for Swift programming
