# Swift Range Operators (... and ..<): Types, Slicing and Pattern Matching

Source: https://devdocs10.com/articles/swift/swift-range-operators  
By Murat Bo · Updated 2026-10-28 · DevDocs10 (https://devdocs10.com)

Swift has two range operators. The closed range operator `a...b` includes both ends, so `1...5` is 1, 2, 3, 4 and 5. The half-open range operator `a..<b` stops before the upper bound, so `0..<5` is 0 through 4, which matches array indices `0..<count`. Leave out one side to get a one-sided range (`2...`, `...2`, `..<2`) for slicing and `switch` cases. Each operator creates a real value (`ClosedRange`, `Range` or a partial range) that stores only its two bounds, and a lower bound above the upper bound crashes the program. This article covers the five range types, loops, slicing arrays and strings, empty and invalid ranges, and how ranges match in `switch` through the `~=` operator.

> **Difficulty:** Beginner
>
> **Helpful to know first:** how a `for-in` loop works, how arrays are indexed from 0, and the basic shape of a `switch` statement.

## How ... and ..< Build a Range Value

A range is not a list of numbers. It is a small value that holds a lower bound, an upper bound and a rule about whether the upper bound counts. The numbers are produced only when you loop over the range or turn it into an array.

```swift
let closed = 1...5
let halfOpen = 0..<5
print(Array(closed))
print(Array(halfOpen))
print(closed.count, halfOpen.count, closed.contains(5), halfOpen.contains(5))
print(MemoryLayout<Range<Int>>.size)
// Output:
// [1, 2, 3, 4, 5]
// [0, 1, 2, 3, 4]
// 5 5 true false
// 16
```

Output (tested with Swift 6.4):

```text
[1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
5 5 true false
16
```

Both ranges have five values, but only the closed one contains 5. A `Range<Int>` is 16 bytes on a 64-bit platform: two `Int` bounds. `0..<1_000_000` takes the same 16 bytes, and `contains` on it is just two comparisons, however wide the range is.

### The five range types

Each form of the operator creates a different standard library type. You rarely write these names, but they appear in error messages and function signatures.

| You write | Type | Contains | Typical use |
| --- | --- | --- | --- |
| `1...5` | `ClosedRange<Int>` | 1 through 5 | Inclusive numbers, allowed values |
| `0..<5` | `Range<Int>` | 0 up to, not including, 5 | Indices and counts; can be empty |
| `2...` | `PartialRangeFrom<Int>` | 2 and everything above | Slice to the end; "90 and up" in a `switch` |
| `...2` | `PartialRangeThrough<Int>` | Everything up to and including 2 | Slice through an index |
| `..<2` | `PartialRangeUpTo<Int>` | Everything below 2 | Slice a prefix; "below 0" in a `switch` |

```swift
print(type(of: 1...5))
print(type(of: 0..<5))
print(type(of: 2...), type(of: ...2), type(of: ..<2))
// Output:
// ClosedRange<Int>
// Range<Int>
// PartialRangeFrom<Int> PartialRangeThrough<Int> PartialRangeUpTo<Int>
```

Output (tested with Swift 6.4):

```text
ClosedRange<Int>
Range<Int>
PartialRangeFrom<Int> PartialRangeThrough<Int> PartialRangeUpTo<Int>
```

The bounds can be any `Comparable` type: `Double`, `String`, `Character` or your own. Every range can answer `contains` and match in a `switch`, but only ranges with integer-like bounds can be looped over (see below).

## Range Examples: Loops, Slices, Strings and Validation

### Repeating work a fixed number of times

Choose the operator by asking whether the last number is part of the job.

```swift
for round in 1...3 {
    print("Round \(round)")
}

let retries = 2
for _ in 0..<retries {
    print("Trying again")
}
// Output:
// Round 1
// Round 2
// Round 3
// Trying again
// Trying again
```

Output (tested with Swift 6.4):

```text
Round 1
Round 2
Round 3
Trying again
Trying again
```

Rounds 1 through 3 include 3, so `...` reads naturally. "Do this `retries` times" is `0..<retries`, which also runs zero times, safely, when `retries` is 0. Ranges always count up by 1; for other steps use [stride](/articles/swift/swift-stride). The [Swift for-in loop](/articles/swift/swift-for-in) article covers the loop itself.

### Slicing an array with closed, half-open and one-sided ranges

Subscripting an array with a range returns the elements at those positions as an `ArraySlice`.

```swift
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
let firstQuarter = months[..<3]
let spring = months[2...4]
let fromApril = months[3...]
print(firstQuarter, spring, fromApril)
print(spring.startIndex, spring.first ?? "-")
print(Array(spring)[0])
// Output:
// ["Jan", "Feb", "Mar"] ["Mar", "Apr", "May"] ["Apr", "May", "Jun"]
// 2 Mar
// Mar
```

Output (tested with Swift 6.4):

```text
["Jan", "Feb", "Mar"] ["Mar", "Apr", "May"] ["Apr", "May", "Jun"]
2 Mar
Mar
```

A one-sided range is completed with the array's own bounds: `months[3...]` means `months[3..<months.count]`. The slice shares storage with the array and keeps the original indices, so `spring` starts at index 2, not 0. `Array(spring)` copies it into a new array that starts at 0. [Swift slices and subsequences](/articles/swift/swift-slices-subsequences) explains slices in depth.

### Taking part of a String with String.Index ranges

Strings use the same operators, but the bounds are `String.Index` values, not integers. A `Character` can take a different number of bytes, so Swift does not pretend that position 4 can be found without walking the string.

```swift
let order = "ORD-2026-0042"
if let dash = order.firstIndex(of: "-") {
    let prefix = order[..<dash]
    let rest = order[order.index(after: dash)...]
    print(prefix, "|", rest)
}

let start = order.index(order.startIndex, offsetBy: 4)
let end = order.index(start, offsetBy: 4)
let year = order[start..<end]
print(year, type(of: year))
// Output:
// ORD | 2026-0042
// 2026 Substring
```

Output (tested with Swift 6.4):

```text
ORD | 2026-0042
2026 Substring
```

Get indices from the string itself, with `firstIndex(of:)`, `index(after:)` or `index(_:offsetBy:)`, then combine them with `..<` or `...`. The result is a `Substring`; wrap it in `String(…)` to store it long term. For the first or last few characters, `prefix(_:)` and `suffix(_:)` need no index math. [Swift Unicode and grapheme clusters](/articles/swift/swift-unicode-graphemes) explains why string indices work this way.

### Classifying values in a switch

Ranges are the natural way to write bands of values as `switch` cases. Matching only needs comparisons, so `Double` ranges work here even though you cannot loop over them.

```swift
func label(forTemperature celsius: Double) -> String {
    switch celsius {
    case ..<0:
        return "freezing"
    case 0..<15:
        return "cold"
    case 15..<25:
        return "mild"
    case 25...:
        return "hot"
    default:
        return "not a number"
    }
}

for t in [-3.5, 0, 14.9, 15, 31, .nan] {
    print(t, label(forTemperature: t))
}
// Output:
// -3.5 freezing
// 0.0 cold
// 14.9 cold
// 15.0 mild
// 31.0 hot
// nan not a number
```

Output (tested with Swift 6.4):

```text
-3.5 freezing
0.0 cold
14.9 cold
15.0 mild
31.0 hot
nan not a number
```

Half-open ranges meet without gaps or overlaps: 15 belongs only to "mild". The `default` is required. Swift does not prove that range cases cover every possible value, so without it the error is `switch must be exhaustive`. Here it also catches `Double.nan`, which compares false with everything and so falls outside every range. More on cases in [Swift switch statements](/articles/swift/swift-switch-statements).

### Validating input with contains, clamped(to:) and overlaps

A range is also a handy way to state a rule once and test values against it.

```swift
let validMonths = 1...12
let input = 13
if validMonths.contains(input) {
    print("Month \(input) is valid")
} else {
    print("Month must be in \(validMonths)")
}

let requested = 40...90
let allowed = 0...60
print(requested.clamped(to: allowed))
print((0..<5).overlaps(5..<10), (0...5).overlaps(5...10))
// Output:
// Month must be in 1...12
// 40...60
// false true
```

Output (tested with Swift 6.4):

```text
Month must be in 1...12
40...60
false true
```

`clamped(to:)` cuts one range down to fit inside another. `overlaps` shows the boundary rule again: `0..<5` and `5..<10` do not share 5, while `0...5` and `5...10` do.

## How Swift Ranges Behave at the Edges

### Empty ranges, and why only Range can be empty

A half-open range with equal bounds contains nothing. A closed range always contains at least its lower bound, so it cannot be empty.

```swift
let empty = 5..<5
print(empty.isEmpty, empty.count, Array(empty))

let single = 5...5
print(single.isEmpty, single.count)

print(Range(1...5), ClosedRange(0..<5))
// Output:
// true 0 []
// false 1
// 1..<6 0...4
```

Output (tested with Swift 6.4):

```text
true 0 []
false 1
1..<6 0...4
```

This is why `0..<items.count` is safe for an empty array: it becomes the empty range `0..<0`. The closed version, `0...items.count - 1`, becomes `0...-1`, which is invalid. The last line shows that you can convert between the two types when the bounds are integers.

### A lower bound above the upper bound crashes

Swift does not create backwards ranges. `5...1` or `5..<1` stops the program at run time. In a debug build the message is `Fatal error: Range requires lowerBound <= upperBound`; in an optimized (`-O`, Release) build the program still crashes, but without the message. When bounds come from variables or user input, check them first or count down with `reversed()` or `stride`. The mistakes section below shows the fix.

### Only integer-like ranges can be looped over

A range is a `Sequence` (and a `Collection`) only when its bound steps by whole numbers: `Int`, `UInt8`, `Int64` and the like. `0.0...1.0` and `"a"..."z"` are valid ranges for `contains` and `switch`, but neither has a whole-number step from one value to the next, so `for-in`, `map` and `count` are not available on them.

### Spacing and precedence

Swift decides whether an operator is binary or one-sided from the spaces around it. `1...5` and `1 ... 5` both work, but `1 ...5` is read as the number 1 followed by the one-sided range `...5`, and fails with `consecutive statements on a line must be separated by ';'`. A one-sided operator must touch its operand: `case ..< 0:` fails with `unary operator cannot be separated from its operand`.

Range formation has lower precedence than arithmetic, so `0..<n - 1` means `0..<(n - 1)` and `1...n * 2` means `1...(n * 2)`, which is usually what you want. See [Swift operator precedence](/articles/swift/swift-operator-precedence) for the full order.

### How switch matches a range: the ~= operator

When a `case` pattern is a value rather than a new name, Swift matches it with the pattern-match operator `~=`. The standard library defines `~=` for ranges to call `contains`, so `case 25...:` is checked as `25... ~= celsius`. You can call it yourself, and `if case` uses the same rule:

```swift
let score = 87
print(80..<90 ~= score)
if case 80..<90 = score {
    print("B grade")
}
// Output:
// true
// B grade
```

Output (tested with Swift 6.4):

```text
true
B grade
```

For a single check, `(80..<90).contains(score)` is easier to read. Knowing about `~=` explains why ranges work in `switch`, and you can define it for your own types (see [Swift pattern matching](/articles/swift/swift-pattern-matching-where)).

## Predict the Output

Both snippets look harmless and do something different from what most people expect.

### Snippet 1: a range of letters

```swift
let letters = "a"..."z"
print(letters.contains("m"))
print(letters.contains("hello"))
print(letters.contains("Z"))
```

Output (tested with Swift 6.4):

```text
true
true
false
```

What does this print?

**Answer:**

It prints `true`, `true`, `false`.

The literals default to `String`, so `letters` is a `ClosedRange<String>`, not a set of 26 letters. `contains` only checks `"a" <= value && value <= "z"` using string ordering, and `"hello"` sorts between them. `"Z"` is uppercase, and uppercase letters sort before lowercase ones, so it is outside. To accept only single characters, annotate `let letters: ClosedRange<Character> = "a"..."z"`; then `letters.contains("hello")` no longer compiles.

### Snippet 2: indexing a slice

```swift
let scores = [70, 85, 90, 65, 100]
let lastThree = scores[2...]
print(lastThree.count)
print(lastThree[0])
```

What happens?

**Answer:**

It prints `3` and then crashes on the last line. In a debug build the message is `Fatal error: Index out of bounds`.

`lastThree` is an `ArraySlice` that keeps the original indices 2, 3 and 4. Index 0 is not one of them. Use `lastThree.first`, `lastThree[lastThree.startIndex]`, or convert with `Array(lastThree)` if you want indices starting at 0.

## Common Range Operator Mistakes and Their Errors

### Looping with 0...array.count

Valid indices of an array stop one before `count`, so a closed range up to `count` goes one step too far.

**Problem:** The last pass uses index 3 on a three-element array. The loop prints all three colors, then crashes with `Fatal error: Index out of range` in a debug build.

```swift
let colors = ["Red", "Green", "Blue"]
for index in 0...colors.count {
    print(colors[index])
}
```

**Fix:** Use a half-open range, or better, the array's own `indices`.

```swift
let colors = ["Red", "Green", "Blue"]
for index in colors.indices {
    print(index, colors[index])
}
// Output:
// 0 Red
// 1 Green
// 2 Blue
```

Output (tested with Swift 6.4):

```text
0 Red
1 Green
2 Blue
```

The corrected version works because `indices` is exactly `0..<colors.count`, and it stays correct for slices that do not start at 0.

### Counting down with a backwards range

`5...1` reads like "from 5 down to 1", but Swift ranges only go up.

**Problem:** The lower bound is greater than the upper bound, so creating the range crashes the program with `Fatal error: Range requires lowerBound <= upperBound` (the message appears in debug builds).

```swift
let start = 5
let end = 1
for n in start...end {
    print(n)
}
```

**Fix:** Build the range the right way round and reverse it, or use `stride` with a negative step.

```swift
let start = 5
let end = 1
print(Array((end...start).reversed()))
print(Array(stride(from: start, through: end, by: -2)))
// Output:
// [5, 4, 3, 2, 1]
// [5, 3, 1]
```

Output (tested with Swift 6.4):

```text
[5, 4, 3, 2, 1]
[5, 3, 1]
```

The corrected version works because `end...start` is a valid range and `reversed()` walks it backwards without copying it.

### Using integer ranges on a String

Code from other languages often slices strings with numbers.

**Problem:** `String` has no integer subscript, so Swift reports `'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.`

```swift
let code = "SWIFT-2026"
let brand = code[0..<5]
```

**Fix:** Use `prefix(_:)` for the start of a string, or build a range from `String.Index` values.

```swift
let code = "SWIFT-2026"
let brand = code.prefix(5)
let yearStart = code.index(code.startIndex, offsetBy: 6)
let year = code[yearStart...]
print(brand, year)
// Output: SWIFT 2026
```

Output (tested with Swift 6.4):

```text
SWIFT 2026
```

The corrected version works because the range operators accept `String.Index` bounds, which the string itself produces.

### Looping over a Double range

`0.0...1.0` is a valid range, so it is easy to expect it to work in a loop.

**Problem:** A `Double` range has no step size, so it is not a `Sequence`. Swift reports `protocol 'Sequence' requires that 'Double.Stride' (aka 'Double') conform to 'SignedInteger'`.

```swift
for opacity in 0.0...1.0 {
    print(opacity)
}
```

**Fix:** Say the step with `stride(from:through:by:)`.

```swift
for opacity in stride(from: 0.0, through: 1.0, by: 0.25) {
    print(opacity)
}
// Output:
// 0.0
// 0.25
// 0.5
// 0.75
// 1.0
```

Output (tested with Swift 6.4):

```text
0.0
0.25
0.5
0.75
1.0
```

The corrected version works because `stride` is given the step that a `Double` range does not have.

## Find the Bug

This function numbers a shopping list. It works for the first list, then the program crashes. Find the bug.

```swift
func printNumbered(_ items: [String]) {
    for i in 0...items.count - 1 {
        print("\(i + 1). \(items[i])")
    }
}

printNumbered(["Milk", "Eggs"])
printNumbered([])
```

**Answer:**

For an empty list, `items.count - 1` is `-1`, so the loop tries to build `0...-1`. A closed range cannot be empty, and its lower bound may not exceed its upper bound, so the program stops with `Fatal error: Range requires lowerBound <= upperBound` before the loop body runs once. The first call prints `1. Milk` and `2. Eggs` and hides the problem.

Use a range that can be empty, or let the array produce its positions:

```swift
func printNumbered(_ items: [String]) {
    for (i, item) in items.enumerated() {
        print("\(i + 1). \(item)")
    }
}

printNumbered(["Milk", "Eggs"])
printNumbered([])
// Output:
// 1. Milk
// 2. Eggs
```

Output (tested with Swift 6.4):

```text
1. Milk
2. Eggs
```

`for i in 0..<items.count` would also work, because `0..<0` is a valid empty range.

## When to Use a Range and When to Use Something Else

| You need | Use |
| --- | --- |
| Loop n times, or over a span of integers | `0..<n` or `1...n` |
| Loop over a collection's positions | `indices` or `enumerated()` |
| A step other than 1, or counting down | `stride(from:to:by:)`, `stride(from:through:by:)` or `reversed()` |
| The first or last few elements | `prefix(_:)`, `suffix(_:)`, `dropFirst(_:)`: they never crash on short collections |
| Check a value against bounds | `(1...12).contains(month)` or a `switch` with range cases |
| Several separate spans of positions | `RangeSet` (added in Swift 6; on Apple platforms it needs macOS 15 or iOS 18 and later) |

The general rule: use `..<` for anything measured from a count or an index, because it can be empty and matches how indices end. Use `...` when the upper value is a real, meaningful member, such as the last day of a month or a top score. More examples of looping over arrays are in [Swift arrays](/articles/swift/swift-arrays).

## Swift Range Interview Questions

### What is the difference between ... and ..<?

`a...b` creates a `ClosedRange` that includes `b`; `a..<b` creates a `Range` that excludes it. Only a half-open range can be empty (`a..<a`), which is why it is the usual choice for indices: `0..<array.count` is valid even for an empty array.

### Why can't you write myString[0..<3] in Swift?

Because `String` is indexed by `String.Index`, not `Int`. Characters are extended grapheme clusters with variable length, so reaching the third character means walking the string. Swift makes that cost visible with `index(_:offsetBy:)` instead of hiding it behind an integer subscript.

## Try It Yourself

- Create `items` as the numbers 1 to 23 using a closed range.
- Write `page(_:of:size:)` that returns the items on a 1-based page as an `[Int]`, using a half-open range to slice.
- The last page may be shorter than `size`.
- A page number below 1 or past the end returns an empty array instead of crashing.
- Print pages 1, 3 and 4 with a page size of 10.

Expected output, one line per page: `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`, then `[21, 22, 23]`, then `[]`.

Hint: the first index of page `n` is `(n - 1) * size`. Cap the end with `min(start + size, items.count)` so the slice never goes past the last index, and check the start before you build the range.

**Solution:**

```swift
func page(_ number: Int, of items: [Int], size: Int) -> [Int] {
    let start = (number - 1) * size
    guard number >= 1, start < items.count else { return [] }
    let end = min(start + size, items.count)
    return Array(items[start..<end])
}

let items = Array(1...23)
print(page(1, of: items, size: 10))
print(page(3, of: items, size: 10))
print(page(4, of: items, size: 10))
// Output:
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// [21, 22, 23]
// []
```

Output (tested with Swift 6.4):

```text
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[21, 22, 23]
[]
```

## Summary

- `a...b` includes both bounds (`ClosedRange`); `a..<b` excludes the upper one (`Range`) and is the one that can be empty.
- One-sided ranges (`a...`, `...b`, `..<b`) are completed by the collection when slicing, and are open-ended in `switch` cases.
- A range stores only its bounds. Any `Comparable` type works for `contains` and `switch`, but only integer-like ranges can be looped over.
- Array slices keep the original indices, and strings need `String.Index` bounds, not integers.
- A lower bound above the upper bound crashes: count down with `reversed()` or `stride`, and loop with `..<` or `indices` so empty collections are safe.
- `switch` matches ranges through `~=`, which calls `contains`; range cases still need a `default`.

A good next step is [iterating with stride](/articles/swift/swift-stride), which covers the custom steps and countdowns that ranges cannot express.
