๐ŸŽ“ A1Learner
๐Ÿ”

Swift Ranges

A range is a span of values between a start value and an end value. One short range can name many values at once.

A closed range holds both ends

Array turns the span into a list so every value shows. The list runs from the start value to the end value.

print(Array(1...5))

A half-open range stops before its end

The list from this form holds one value less than the closed form. Its last value is 4 and not 5.

print(Array(1..<5))

Count and membership checks

A count tells how many values a span holds. A contains check tells whether a single value lies inside the span.

print((1...5).count)
print((1...5).contains(3))
print((1...5).contains(9))

Stepping with stride

stride starts at a first value and adds the same gap on each step. Array collects the stepped values into a list.

print(Array(stride(from: 0, to: 10, by: 3)))

A range inside a switch case

The value 7 falls in the second span here. That case prints the top value of its span.

let score = 7
switch score {
case 1...5:
    print(5)
case 6...10:
    print(10)
default:
    print(0)
}

Example

print(Array(2...6))
print((2...6).count)
print((2...6).contains(6))
print(Array(stride(from: 2, to: 12, by: 5)))

Key points

  • A range starts at its first value and ends at its last value.
  • Three dots between two values make a closed range that includes both ends.
  • The symbols ..< between two values make a half-open range.
  • Both forms step upward by one from the start value to the end value.
  • A range can stand in a switch case in place of one single value.

In this example, the first line turns the closed range 2...6 into a list and prints [2, 3, 4, 5, 6]. The second line prints the count of that range, which is 5. The third line checks whether 6 lies inside the range and prints true. The last line steps from 2 by 5 toward 12 and prints [2, 7].

Note

The end value of a stride call stays out of the stepped values, just like a half-open end.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

What does print(Array(1..<4)) print?