Swift for Loop

Swift Tutorial

🔁 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

for variable in sequence {
// code
}

Example


Output

1
2
3
4
5

3️⃣ Closed Range vs Half-Open Range ⭐⭐

Closed Range (...)


Output:

1
2
3

Half-Open Range (..<)


Output:

1
2

4️⃣ Loop Without Using Variable ⭐⭐


Output

Hello
Hello
Hello

5️⃣ for Loop with Arrays ⭐⭐


 

Output

Apple
Banana
Mango

6️⃣ for Loop with Dictionary ⭐⭐⭐


 

Output (order may vary)

Math: 90
Science: 85

7️⃣ for Loop with String ⭐⭐


 

Output

S
w
i
f
t

8️⃣ Using stride() for Steps ⭐⭐⭐

Increment


Output:

1
3
5
7
9

Decrement


Output:

10
8
6
4
2

9️⃣ Using break and continue ⭐⭐

break


Output:

1
2
3

continue


Output:

1
2
4
5

🔟 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

You may also like...