Menu
Coddy logo textTech

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, 3

The 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, 2

Sometimes 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, 1

Notice 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 icon

Challenge

Easy
Write 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 1 to n and 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, 3

The half-open range operator (..<) excludes the upper bound:

for i in 0..<3 {
    print(i)
}
// Output: 0, 1, 2

To iterate backwards through a range, use the reversed() method:

for i in (1...3).reversed() {
    print(i)
}
// Output: 3, 2, 1

Note: Parentheses around the range are required when calling reversed().

Try it yourself

func countdown(n: Int) -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals