StructureSwift

ClosedRange

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

@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.

Members

Typealiases

  • typealias Element

    A type representing the sequence’s elements.

  • typealias Iterator

    A type that provides the sequence’s iteration interface and encapsulates its iteration state.

  • typealias SubSequence

    A collection representing a contiguous subrange of this collection’s elements. The subsequence shares indices with the original collection.

Initializers

Instance Subscripts

Instance Properties

Instance Methods

Operators

Enumerations

  • enum Index

    A type that represents a position in the collection.

Conforms To

Removed Members

Initializers

  • init(ClosedRange<Bound>)

    Now that Range is conditionally a collection when Bound: Strideable, CountableRange is no longer needed. This is a deprecated initializer for any remaining uses of Range(countableRange).

    • Obsolete since Swift 5.0