Countable ranges are one of Swift’s unique features that are quite common in for
and switch
statements.
What are countable ranges
Countable ranges are simply a sequence of increasing numbers within a specific range.
These are divided into two types, the closed ranges and the half-open ranges.
💡 If you noticed the small emphasis on the word “increasing” in the previous sentence, it is because this is a rule within both types of ranges, the second number of the range must be equal to or greater than the first number.
Closed Range
This type of sequence goes from the first number to the second number, including the second number as part of the sequence, and is denoted as follows lower...upper
, where lower equals the lowest number in the sequence and upper the bigger number.
An interval from a lower bound up to, and including, an upper bound. developer.apple.com
for index in 10...15 {
print("Index: \(index)")
}
In the previous code, we can see a for
statement that prints the indices within the sequence, this will go from 10 to 15 including the latter, so we will obtain the following
Index: 10
Index: 11
Index: 12
Index: 13
Index: 14
Index: 15
Half-open Range
This type of sequence goes from the first number to the second number, without including the second number as part of the sequence and is denoted as follows lower ..< upper
, where lower equals the lowest number in the sequence and upper to the bigger number.
A half-open interval from a lower bound up to, but not including, an upper bound. developer.apple.com
for index in 10..<15 {
print("Index: \(index)")
}
In the previous code, we can see a for
statement that prints the indices within the sequence, this will go from 10 to 14 since we do not include the largest number, so we will obtain the following
Index: 10
Index: 11
Index: 12
Index: 13
Index: 14
Conclusion
Although ranges are not a complex topic, we usually ignore their existence, we can denote 3 important points from this.
- Closed range is denoted using
...
. - The half-open range is denoted using
..<
. - Fairly common within
for
andswitch
statements. - The number on the far right must be greater than or equal to the number on the far left.
I hope this article helps you, I’ll appreciate it if you can share it and #HappyCoding👨💻.