Swift while Loop
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
2️⃣ Simple while Loop Example ⭐
Output
3️⃣ while Loop with Condition ⭐⭐
Output
4️⃣ Infinite while Loop ⚠️
❌ Condition never becomes false
📌 Causes infinite loop
✔ Correct way:
5️⃣ while Loop with User Input ⭐⭐
Sample Input
Output
6️⃣ while Loop with Boolean ⭐⭐
Output
7️⃣ while vs repeat-while ⭐⭐⭐
while Loop
📌 May execute 0 times
repeat-while Loop
📌 Executes at least once
8️⃣ Using break and continue ⭐⭐
break
Output:
continue
Output:
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
