Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 146 ยท Control Flow

Ranges

Learn Swift ranges - closed ... and half-open ..< ranges, one-sided and partial ranges, ClosedRange and Range types, contains, clamped, slicing and iteration limits.

A range describes everything between two values: the numbers 1 through 10, the indices of an array, the temperatures from 15 to 25 degrees. Swift gives you a small family of range operators that you will use constantly in loops, switch statements, array slicing and validation. They look simple, but each one is a real type with its own rules about what it can and cannot do, and the differences explain several beginner errors.

This lesson covers the closed range ..., the half-open range ..<, the one-sided and unbounded forms, the types behind them (ClosedRange, Range and their partial cousins), how to test membership, how to clamp a value into a range, how to slice collections, why some ranges cannot be looped over, and where stride takes over. You have already met ranges in Loops; here we study them in their own right.

Closed and half-open ranges

The closed range operator a...b includes both ends. The half-open range operator a..<b includes a but excludes b.

Swift The two basic ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The types differ: 1...5 is a ClosedRange<Int> and 1..<5 is a Range<Int>. Both are generic over any Comparable type. Half-open ranges are the natural fit for zero-based indexing, because 0..<array.count says "all valid indices" with no - 1 to forget, and the number of elements in a..<b is simply b - a. A closed range reads more naturally for human numbers ("pages 1 through 10") and is the only one that can contain the maximum value of a type, so 0...Int.max is possible where 0..<Int.max + 1 would overflow.

An empty range is allowed when both ends are equal and the range is half-open: 3..<3 has no elements. A closed range always contains at least its lower bound, so 3...3 has one element.

Swift Empty and single-element ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The lower bound must not exceed the upper bound

Both range types require lowerBound <= upperBound. Writing it the wrong way round is a bug, not an empty range, and the program traps at run time (when the bounds are literals, the compiler catches it). Variables are the usual way this happens:

Swift An upside-down range (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program dies with an illegal-instruction signal (SIGILL) on our optimized runner (text that was still waiting in the output buffer can be lost when a program crashes, so the first print may not show up); a debug build stops with a fatal error saying that the range requires a lower bound that is not greater than the upper bound. Fixes: check the order first (guard start <= end), build the range with min/max, or count down with stride(from:through:by:) or (end...start).reversed().

One-sided and unbounded ranges

Leave out one end and Swift infers it from context. These are the partial ranges: a... (from a upward), ...b (up to and including b), and ..<b (up to but not including b). The completely unbounded ... also exists, mainly for subscripts.

Swift One-sided ranges slice collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Slicing an Array gives an ArraySlice, and slicing a String gives a Substring. Both share storage with the original and keep the original indices: letters[2...] starts at index 2, not at 0. This is the single most common surprise with slices; Ranges and Slices and Arrays go into it. Convert to a new array when you need fresh indices: Array(letters[2...]).

Out-of-bounds ranges trap just like out-of-bounds indices. letters[4...8] stops the program, because index 8 does not exist.

A one-sided range has no fixed size, so it cannot say how many elements it holds. PartialRangeFrom (the 1... form) can be iterated (it counts upward forever), and is handy with zip or enumerated-style numbering, while PartialRangeThrough and PartialRangeUpTo cannot be iterated at all because they have no start.

Testing membership with contains and ~=

contains tells you whether a value lies inside a range. It works for any Comparable bounds, including Double and String, so ranges are not only for counting:

Swift contains, and ranges of Double and Character

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Under the hood, switch uses the pattern match operator ~=, which is defined for ranges (the pattern 13...19 matches any value that the range contains). Because Double is not stridable by whole steps, a range of doubles has no count and no elements to iterate; it only answers membership questions. The switch above is exhaustive for numbers thanks to the default; the compiler cannot prove that ..<10, 10..<20 and 20... cover every Double (NaN is the exception).

Two ranges can also be compared with each other:

Swift overlaps and clamped

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

overlaps is handy for scheduling and collision checks, and it correctly handles the open/closed distinction. clamped(to:) on a range is in the standard library: it returns the part of one closed range that fits inside another. Clamping a single value is not built in, so you write it yourself.

Writing a clamp

For one value, combine min and max. A tiny extension makes that reusable, and is also a good first generic function:

Swift A clamped(to:) extension

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

An extension adds methods to an existing type; here it adds clamped(to:) to everything that is Comparable. See Nested Types and Extensions for details. Clamping is useful for volume sliders, array index safety, progress bars and any "keep this between limits" rule.

Why some ranges cannot be looped over

You can loop over a range only when its bound type is strideable by whole steps, which means it conforms to Strideable with an integer Stride. Int qualifies. Double does not: what comes after 0.5 in 0.0...1.0? Swift refuses to guess.

Swift Looping over a Double range (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler answers main.swift:1:13: error: protocol 'Sequence' requires that 'Double' conform to 'SignedInteger', because a range is a Sequence only when the distance between two bounds is an integer. Tell Swift the step yourself with stride(from: 0.0, through: 1.0, by: 0.25), which works for any Strideable type and is the right tool when the step is not 1 or when you count down. Another way is to loop over integers and compute the value: for i in 0...4 { let x = Double(i) / 4 }, which avoids accumulating floating-point error.

Characters have the same limitation as doubles: "a"..."e" works for contains, but you cannot iterate it. Use the Unicode scalar values (Unicode.Scalar("a").value) or a string such as "abcde" if you want to loop over letters.

Ranges as values

Because ranges are ordinary values, you can store them, pass them to functions and use them in arrays and dictionaries. A common use is a lookup table of grade bands:

Swift Ranges stored in data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Functions that accept ranges should say which kind they need. Range<Int> accepts only a..<b, ClosedRange<Int> only a...b, and the protocol RangeExpression accepts all of them, including one-sided ranges. The standard library uses RangeExpression for subscripts, which is why array[2...] and array[..<3] both compile. A Range<Int> can be created from a closed range with Range(closedRange) when the upper bound can be incremented.

stride, once more

For steps other than 1, use stride. It is the right choice when a range would be awkward:

Swift Choosing between ranges and stride

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first argument names are to: (exclusive) or through: (inclusive), and the step may be negative. The result is a sequence; wrap it in Array(...) if you need an array.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many elements are in 3..<7?

    A half-open range includes 3, 4, 5 and 6, which is 7 - 3 = 4 elements.
  2. 2. What is the type of 1...5?

    The ... operator creates a ClosedRange; ..< creates a Range.
  3. 3. Why does for x in 0.0...1.0 { } not compile?

    Only ranges over strideable-by-integer types such as Int can be iterated. Doubles support contains and overlaps, and you can loop with stride.
  4. 4. If let a = [10, 20, 30, 40, 50], what is a[2...][0]?

    A slice keeps the indices of the original array. The slice starts at index 2, so its first element is a[2], which is 30.
  5. 5. What happens at run time with let lo = 5, hi = 2 and for i in lo...hi?

    Ranges require lowerBound <= upperBound. Use stride or reversed() to count down.

Summary

  • a...b is a ClosedRange (both ends included); a..<b is a Range (upper end excluded). Half-open ranges fit zero-based indexing.
  • Both require lowerBound <= upperBound; an upside-down range is a runtime trap, not an empty range.
  • a..., ...b and ..<b are partial ranges, used mostly to slice collections; slices keep the original indices.
  • contains, overlaps and the switch pattern work for any Comparable bounds, including Double, String and Character.
  • Only integer-like ranges are sequences you can loop over; use stride for steps, countdowns and Double values.
  • Write a small clamped(to:) extension (or combine min and max) to keep values inside limits.

Next: Tuples