Contents

ClosedRange

An interval from a lower bound up to, and including, an upper bound.

Declaration

@frozen struct ClosedRange<Bound> where Bound : Comparable

Overview

You create a ClosedRange instance by using the closed range operator (...).

let throughFive = 0...5

A ClosedRange instance contains both its lower bound and its upper bound.

throughFive.contains(3)
// true
throughFive.contains(10)
// false
throughFive.contains(5)
// true

Because a closed range includes its upper bound, a closed range whose lower bound is equal to the upper bound contains that value. Therefore, a ClosedRange instance cannot represent an empty range.

let zeroInclusive = 0...0
zeroInclusive.contains(0)
// true
zeroInclusive.isEmpty
// false

Using a Closed Range as a Collection of Consecutive Values

When a closed range uses integers as its lower and upper bounds, or any other type that conforms to the Strideable protocol with an integer stride, you can use that range in a for-in loop or with any sequence or collection method. The elements of the range are the consecutive values from its lower bound up to, and including, its upper bound.

for n in 3...5 {
    print(n)
}
// Prints "3"
// Prints "4"
// Prints "5"

Because floating-point types such as Float and Double are their own Stride types, they cannot be used as the bounds of a countable range. If you need to iterate over consecutive floating-point values, see the stride(from:through:by:) function.

Topics

Creating a Range

Converting Ranges

Inspecting a Range

Checking for Containment

Clamping a Range

Comparing Ranges

Manipulating Indices

Describing a Range

Encoding and Decoding a Range

Infrequently Used Functionality

Initializers

Instance Methods

Default Implementations

See Also

Ranges