What if your computer could do boring counting for you, perfectly every time?
Why While loop in Swift? - Purpose & Use Cases
Imagine you want to count from 1 to 10 by writing each number down manually. You write 1, then 2, then 3, and so on until 10.
This manual counting is slow and boring. If you want to count to 100 or 1000, it becomes a huge chore and easy to make mistakes like skipping numbers or writing the wrong one.
A while loop lets the computer do the counting for you automatically. It keeps repeating the counting step until it reaches the number you want, saving you time and avoiding errors.
var count = 1 print(count) count += 1 print(count) count += 1 print(count) // and so on...
var count = 1 while count <= 10 { print(count) count += 1 }
With while loops, you can easily repeat tasks many times without writing repetitive code, making programs smarter and faster.
Think about a game where you want to keep asking the player to guess a number until they get it right. A while loop keeps asking until the correct guess is made.
Manual repetition is slow and error-prone.
While loops automate repeated actions until a condition changes.
This makes programs efficient and easier to write.