0
0
Swiftprogramming~5 mins

For-in loop with ranges in Swift

Choose your learning style9 modes available
Introduction

A for-in loop with ranges helps you repeat actions a set number of times easily.

When you want to count from 1 to 5 and do something each time.
When you need to repeat a task exactly 10 times.
When you want to go through numbers between two values.
When you want to print numbers in order.
When you want to create a list of numbers using a loop.
Syntax
Swift
for number in start...end {
    // code to repeat
}

The three dots (...) create a closed range including both start and end.

You can also use two dots (..<) for a half-open range that excludes the end.

Examples
This prints numbers 1 through 5, including 5.
Swift
for i in 1...5 {
    print(i)
}
This prints numbers 0, 1, 2 but not 3.
Swift
for i in 0..<3 {
    print(i)
}
This runs the loop once with i equal to 5.
Swift
for i in 5...5 {
    print(i)
}
Sample Program

This program prints a message for each number from 1 to 5.

Swift
for number in 1...5 {
    print("Number is \(number)")
}
OutputSuccess
Important Notes

Ranges are very useful to control how many times a loop runs.

Using a half-open range (..<) is common when working with arrays to avoid going out of bounds.

Summary

For-in loops with ranges repeat code for each number in the range.

Closed ranges (start...end) include the last number.

Half-open ranges (start..