Swift Ranges
Swift Ranges
Use ranges to express a sequence of values.
a...b is a closed range including both ends.
a..<b is a half-open range up to but not including b.
Closed and Half-Open
Use a...b for closed ranges (inclusive) and a..<b for half-open ranges (exclusive upper bound).
Example
for n in 1...5 {
print(n)
}
for n in 1..<5 {
print(n)
}
let r = 10...12
print(r.contains(11))
print(r.contains(13))
This example iterates over closed and half-open ranges and checks membership with contains().
One-Sided Ranges
One sided ranges omit one end: ...b starts from the beginning, and a... goes to the end.
Example
let arr = [0, 1, 2, 3, 4]
print(arr[...2]) // first three elements (indices 0...2)
print(arr[2...]) // from index 2 to the end
This example slices an array using one sided ranges: up to and including index 2, and from index 2 to the end.