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.
Range operators (... and ..<) in 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.
1...51..<5
for i in 1...3 { print(i) }
for i in 1..<3 { print(i) }
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.
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) }
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.
Range operators create sequences of numbers easily.
... includes both start and end numbers.
..< includes start but excludes end number.