Ranges In Loops
Part of the Fundamentals section of Coddy's Swift journey — lesson 48 of 86.
You've been using ranges like 1...5 in your loops, but Swift offers more flexibility in how you define these ranges. Let's explore the different range types and a useful technique for counting backwards.
The closed range operator (...) includes both endpoints:
for i in 1...3 {
print(i)
}
// Output: 1, 2, 3The half-open range operator (..<) excludes the upper bound, which is especially useful when working with zero-based indices:
for i in 0..<3 {
print(i)
}
// Output: 0, 1, 2Sometimes you need to loop in reverse order. The reversed() method lets you iterate backwards through a range:
for i in (1...3).reversed() {
print(i)
}
// Output: 3, 2, 1Notice the parentheses around the range—they're required when calling reversed() on a range. This technique is perfect for countdowns or when you need to process items from last to first.
Challenge
EasyWrite a function countdown that takes n and returns a string containing a countdown from n down to 1, followed by "Go!".
Use the reversed() method on a range to iterate backwards and build the countdown string.
Logic:
- Create a range from
1tonand reverse it - Build a string with each number separated by a newline
- Add "Go!" on the final line
Parameters:
n(Int): The starting number for the countdown (1 or greater)
Returns: A string with each countdown number on its own line, ending with "Go!" (String). Format:
3
2
1
Go!For example, if n is 3, the function returns "3\n2\n1\nGo!".
Cheat sheet
Swift provides two range operators for loops:
The closed range operator (...) includes both endpoints:
for i in 1...3 {
print(i)
}
// Output: 1, 2, 3The half-open range operator (..<) excludes the upper bound:
for i in 0..<3 {
print(i)
}
// Output: 0, 1, 2To iterate backwards through a range, use the reversed() method:
for i in (1...3).reversed() {
print(i)
}
// Output: 3, 2, 1Note: Parentheses around the range are required when calling reversed().
Try it yourself
func countdown(n: Int) -> String {
// 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