Swift Ranges
In Swift, a range is a series of values between two numeric intervals.

...
is a range operator1...4
contains values 1, 2, 3, 4- 1 is lower bound (first element)
- 4 is upper bound (last element)
Types of Range in Swift
1. Closed Range
A closed range includes all the values in the interval from the lower bound to the upper bound.
It is declared using the ...
(3 dots) operator. For example,
// 1...4 is close range
for numbers in 1...4 {
print(numbers)
}
Output
1
2
3
4
2. Half-Open Range
A half-open range includes all the values from the lower bound to the upper bound. However, it excludes the upper bound (last number).
It is declared using the ..<
operator.
for numbers in 1..<4 {
print(numbers)
}
Output
1
2
3
3. One-sided Range
We can create a one-sided range using either of the ...
or the ..<
operator.
A one-sided range contains elements up to infinite in one direction.
let range1 = ..<2
Here, ...<2
is a one-sided range. It contains all elements from 2 to -∞. Similarly, the range
let range2 = 2...
contains all elements from 2 to +∞.
We can verify this by checking if a certain number is present in the range. For example,
// one-sided range using
// ..< operator
let range1 = ..<2
// check if -9 is in the range
print(range1.contains(-1))
// one-sided range using
// ... operator
let range2 = 2...
// check if 33 is in the range
print(range2.contains(33))
Output
true
true