A closed range includes all the values in the interval from the lower bound to the upper bound.
// 1...4 is close range
for numbers in 1...4 {
print(numbers)
Output
In the above example, we have created a closed range
1...4
.
Since it is a closed range, it contains all the numbers between
1
to
4
including the lower bound (
1
) and upper bound (
4
).
Here, we have used the
Swift for loop
to access all the values in the range.
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).
In the above example, we have created a half-open range
1..<4
. Since it is a half-open range, it excludes the upper bound element
4
.
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. For example,
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
Here, we have used
contains()
method to check if a certain number is present in the range.
Note:
With a one-sided range, we only set either upper bound or lower bound.
Access Array Elements Using Swift Range
We can also use the Swift range to access
array
elements. For Example,
let languages = ["Swift", "Java", "C"]
// access array elements
print(languages[0...2])
Output
["Swift", "Java", "C"]
Here, the range
0...2
acts as array indices and helps us access all array elements.
Things to Remember About Swift Range
1. The lower bound value must be smaller than the upper bound value. For example,
// Invalid Range
3...1
// Valid Range
1...3
2. The lower bound and upper bound value can be negative. For example,
// negative lower bound
-3...1
// negative upper and lower bound
-9...-2