Swift while Loop

Swift Tutorial

s🔁 Swift while Loop – Complete Beginner to Interview Guide

In Swift, the while loop is used to repeat a block of code as long as a condition is true.
It is best used when the number of iterations is not known in advance.


1️⃣ What is while Loop in Swift? ⭐

  • Condition is checked before executing the loop body

  • Loop runs until the condition becomes false

Syntax

while condition {
// code to execute
}

2️⃣ Simple while Loop Example ⭐


 

Output

1
2
3
4
5

3️⃣ while Loop with Condition ⭐⭐


 

Output

10
9
8
7
6
5
4
3
2
1

4️⃣ Infinite while Loop ⚠️


 

❌ Condition never becomes false
📌 Causes infinite loop

✔ Correct way:


5️⃣ while Loop with User Input ⭐⭐


 

Sample Input

5
3
2
0

Output

Total = 10

6️⃣ while Loop with Boolean ⭐⭐


 

Output

Loop Running

7️⃣ while vs repeat-while ⭐⭐⭐

while Loop

while condition {
// code
}

📌 May execute 0 times


repeat-while Loop

repeat {
// code
} while condition

📌 Executes at least once


8️⃣ Using break and continue ⭐⭐

break


 

Output:

1
2

continue


 

Output:

1
2
4
5

9️⃣ Common Mistakes ❌

❌ Forgetting to update loop variable
❌ Writing wrong condition
❌ Infinite loops
❌ Force unwrapping user input unsafely


📌 Interview Questions (Swift while Loops)

Q1. When to use while loop?
👉 When number of iterations is unknown

Q2. Difference between while and repeat-while?
👉 repeat-while executes at least once

Q3. What causes infinite loop?
👉 Condition never becomes false


✅ Summary

while loop checks condition first
✔ Used when iterations are unknown
✔ Can become infinite if not careful
break and continue control loop
✔ Very important for Swift interviews

You may also like...