While Loop
Part of the Fundamentals section of Coddy's Swift journey — lesson 43 of 86.
Sometimes you don't know exactly how many times a loop should run. Instead, you want to keep looping while a condition remains true. That's where the while loop comes in.
var count = 1
while count <= 3 {
print(count)
count += 1
}
// Output: 1, 2, 3 (each on a new line)The loop checks the condition count <= 3 before each iteration. As long as it's true, the code inside runs. Once the condition becomes false, the loop stops.
Be careful: if the condition never becomes false, you'll create an infinite loop! Always make sure something inside the loop eventually changes the condition:
var number = 10
while number > 0 {
print(number)
number -= 2
}
// Output: 10, 8, 6, 4, 2Use a while loop when the number of iterations depends on a condition that changes during execution, rather than a fixed range.
Challenge
EasyWrite a function countdownSum that takes start and returns the sum of all numbers from start down to 1.
Use a while loop to count down from the starting number, adding each value to a running total until you reach zero.
Logic:
- Start with the given number
- While the number is greater than 0, add it to the sum and decrease by 1
- Return the final sum
Parameters:
start(Int): The starting number for the countdown
Returns: The sum of all numbers from start down to 1 (Int)
For example, if start is 5, the function calculates 5 + 4 + 3 + 2 + 1 = 15 and returns 15.
Cheat sheet
A while loop repeats code as long as a condition is true:
var count = 1
while count <= 3 {
print(count)
count += 1
}
// Output: 1, 2, 3The condition is checked before each iteration. When it becomes false, the loop stops.
Always ensure the condition eventually becomes false to avoid infinite loops:
var number = 10
while number > 0 {
print(number)
number -= 2
}
// Output: 10, 8, 6, 4, 2Use while loops when the number of iterations depends on a changing condition rather than a fixed range.
Try it yourself
func countdownSum(start: Int) -> Int {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input