Swift repeat while Loop

Swift Tutorial

🔁 Swift repeat while Loop – Complete Beginner to Interview Guide

In Swift repeat while Loop is used to execute a block of code at least once, and then repeat it as long as a condition is true.


1️⃣ What is repeat-while Loop? ⭐

  • Condition is checked after executing the loop body

  • Loop runs minimum one time

  • Similar to do–while loop in other languages


2️⃣ Syntax of repeat-while

repeat {
// code to execute
} while condition

📌 Note: Semicolon is NOT requiring


3️⃣ Simple repeat-while Example ⭐


 

Output

1
2
3
4
5

4️⃣ Difference Between while and repeat-while ⭐⭐

while Loop


 

Output:

(no output)

repeat-while Loop


 

Output:

10

📌 repeat-while runs once even if condition is false


5️⃣ repeat-while with User Input ⭐⭐


 

Sample Input

5
3
0

📌 Loop stops when user enters 0


6️⃣ repeat-while with Boolean ⭐⭐


 

Output

Running once

7️⃣ Using break and continue ⭐⭐

break


 

Output:

1
2

continue


 

Output:

1
2
4
5

8️⃣ Common Mistakes ❌

❌ Forgetting to update condition variable
❌ Infinite loop
❌ Wrong condition logic
❌ Unsafe force unwrap (!) of input


📌 Interview Questions (Swift repeat-while)

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

Q2. Is semicolon required after while?
👉 No

Q3. When should repeat-while be used?
👉 When code must run at least once


✅ Summary

repeat-while runs at least once
✔ Condition checked at the end
✔ Useful for user input validation
✔ Similar to do–while
✔ Important for Swift interviews

You may also like...