Understanding While Loops in Swift
A while loop in Swift is used to repeatedly execute a block of code
as long as a specified condition remains true. This loop is
particularly useful when the number of iterations is unknown
beforehand.
Unlike for loops, which iterate a predefined number of times, a
while loop will only stop executing when its condition evaluates to
false. This helps in cases where dynamic conditions dictate the
number of loop iterations.
Key Characteristics of While Loops
- The loop may never execute if the condition is initially false.
- If the condition remains true indefinitely, the loop may lead to an infinite loop, which should be avoided.
- It is crucial to update variables within the loop to eventually meet the stopping condition.
Syntax of a While Loop in Swift
while condition{
// Code to execute
}
condition: A Boolean expression that determines whether the loop
executes.
The loop runs while condition is true. Once condition is false,
execution moves to the next statement after the loop.
Example 1: Printing Numbers Using a While Loop
Let's take a look at a simple example where we print numbers from 5 to 15.
import
Foundation
var number =
5
while number
<=
print(
"Current number is \(number) "
)
number += 1
}
Output
Current number is 6
Current number is 7
Current number is 8
Current number is 9
Current number is 10
Current number is 11
Current number is 12
Current number is 13
Current number is 14
Current number is 15
Example 2: Calculating Factorial Using a While Loop
Let's compute the factorial of a number using a while loop.
var num =
5
var factorial
= 1
while num >
0 {
factorial *= num
num -= 1
}
print(
"Factorial of 5 is: \(factorial)"
)