Swift forEach Loop

🔁 Swift forEach Loop – Complete Beginner to Interview Guide
In Swift forEach Loop is a method used to iterate over collections such as arrays, dictionaries, and sets.
It provides a clean, functional-style way to loop through data.
1️⃣ What is forEach in Swift? ⭐
forEachis a method, not a keywordUsed with collections
Executes a closure for each element
Part of Swift’s functional programming style
2️⃣ Basic forEach Syntax ⭐
3️⃣ forEach with Array ⭐
Output
4️⃣ forEach with Dictionary ⭐⭐
Output (order may vary)
5️⃣ forEach with Set ⭐⭐
Output (order may vary)
6️⃣ Short Syntax Using $0 ⭐⭐
📌 $0 represents the current element
7️⃣ forEach vs for-in Loop ⭐⭐⭐
| Feature | forEach | for-in |
|---|---|---|
Control flow (break) | ❌ Not allowed | ✅ Allowed |
continue | ❌ Not allowed | ✅ Allowed |
| Functional style | ✅ Yes | ❌ No |
| Readability | ✅ Clean | ✅ Flexible |
8️⃣ ❌ What You CANNOT Do in forEach ⚠️
📌 break and continue do not work in forEach.
✔ Use return to skip current iteration:
9️⃣ forEach with Index ⭐⭐
Output
🔟 When to Use forEach ❓
✔ Simple iteration
✔ Functional programming style
✔ Clean, readable code
❌ Avoid when:
You need
breakorcontinueYou need complex loop control
📌 Interview Questions (Swift forEach)
Q1. Is forEach a loop or function?
👉 Function (method)
Q2. Can we use break in forEach?
👉 No
Q3. Which is better: forEach or for-in?
👉 Depends on use case
✅ Summary
✔ forEach iterates collections
✔ Uses closure syntax
✔ Clean & functional
✔ No break or continue
✔ Best for simple loops
