Swift forEach Loop

Swift Tutorial

🔁 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? ⭐

  • forEach is a method, not a keyword

  • Used with collections

  • Executes a closure for each element

  • Part of Swift’s functional programming style


2️⃣ Basic forEach Syntax ⭐

collection.forEach { element in
// code
}

3️⃣ forEach with Array ⭐


 

Output

1
2
3
4
5

4️⃣ forEach with Dictionary ⭐⭐


 

Output (order may vary)

Math: 90
Science: 85

5️⃣ forEach with Set ⭐⭐


 

Output (order may vary)

Apple
Banana
Mango

6️⃣ Short Syntax Using $0 ⭐⭐


 

📌 $0 represents the current element


7️⃣ forEach vs for-in Loop ⭐⭐⭐

FeatureforEachfor-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 ⚠️

numbers.forEach {
if $0 == 3 {
break // ❌ Error
}
}

📌 break and continue do not work in forEach.

✔ Use return to skip current iteration:

numbers.forEach {
if $0 == 3 {
return
}
print($0)
}

9️⃣ forEach with Index ⭐⭐



 

Output

Index: 0 Value: 1
Index: 1 Value: 2
Index: 2 Value: 3
...

🔟 When to Use forEach

✔ Simple iteration
✔ Functional programming style
✔ Clean, readable code

❌ Avoid when:

  • You need break or continue

  • You 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

You may also like...