4.5. Range operators
Swift can even represent a range of values. There are two kinds of range operators in Swift:
Closed range operators (
...) creates ranges up to and including the final value.Half-open range operators (
..<) creates ranges up to and excluding the final value.
For example, the range 1..5 contains the numbers 1, 2, 3, 4, and 5. In contrast, the range 1..<5 contains the numbers 1, 2, 3, and 4.
The ranges are most useful in switch statements. For example, let's revisit the week example from before. We can write the following code:
let today = 8
switch today{
case 1...5:
print("Weekday!")
case 6..<8:
print("Weekend!")
default:
print("Invalid day!")
}It means that if the value of today is in the range 1 to 5 (including 5), today is a weekday; if the value is in the range 6 to less than 8, today is a weekend; else it is an invalid day.
Last updated
Was this helpful?