0
0
Swiftprogramming~5 mins

Range operators (... and ..<) in Swift

Choose your learning style9 modes available
Introduction

Range operators help you create a sequence of numbers easily. They let you pick numbers between a start and an end without writing each one.

When you want to repeat something a certain number of times.
When you need to access parts of a list or array by position.
When you want to check if a number falls within a certain range.
When you want to loop through numbers from one value up to another.
When you want to create a list of numbers quickly for calculations.
Syntax
Swift
start...end   // Closed range: includes start and end
start..<end   // Half-open range: includes start but excludes end

The ... operator creates a range that includes both the start and the end numbers.

The ..< operator creates a range that includes the start number but stops just before the end number.

Examples
This means numbers 1, 2, 3, 4, and 5 are included.
Swift
1...5
This means numbers 1, 2, 3, and 4 are included, but not 5.
Swift
1..<5
This loop prints numbers 1, 2, and 3.
Swift
for i in 1...3 {
    print(i)
}
This loop prints numbers 1 and 2 only.
Swift
for i in 1..<3 {
    print(i)
}
Sample Program

This program shows how both range operators work by printing numbers from 1 to 5 using the closed range, and from 1 up to but not including 5 using the half-open range.

Swift
import Foundation

// Using closed range operator
print("Closed range 1...5:")
for number in 1...5 {
    print(number)
}

// Using half-open range operator
print("\nHalf-open range 1..<5:")
for number in 1..<5 {
    print(number)
}
OutputSuccess
Important Notes

Use the closed range ... when you want to include the last number in your range.

Use the half-open range ..< when you want to exclude the last number, which is useful for zero-based indexes like arrays.

Ranges work well with loops and conditions to make your code simpler and cleaner.

Summary

Range operators create sequences of numbers easily.

... includes both start and end numbers.

..< includes start but excludes end number.