0
0
Swiftprogramming~3 mins

Why While loop in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your computer could do boring counting for you, perfectly every time?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
var count = 1
print(count)
count += 1
print(count)
count += 1
print(count) // and so on...
After
var count = 1
while count <= 10 {
    print(count)
    count += 1
}
What It Enables

With while loops, you can easily repeat tasks many times without writing repetitive code, making programs smarter and faster.

Real Life Example

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.

Key Takeaways

Manual repetition is slow and error-prone.

While loops automate repeated actions until a condition changes.

This makes programs efficient and easier to write.