Generic Structure

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

Create a new range using the closed range operator (...).

static func ... (Self, Self) -> ClosedRange<Self>

Returns a closed range that contains both of its bounds.

Converting Ranges

func relative<C>(to: C) -> Range<Bound>

Returns the range of indices described by this range expression within the given collection.

init(Range<Bound>)

Creates an instance equivalent to the given Range.

Inspecting a Range

var isEmpty: Bool

A Boolean value indicating whether the range contains no elements.

var count: Int

The number of elements in the collection.

let lowerBound: Bound

The range’s lower bound.

let upperBound: Bound

The range’s upper bound.

Checking for Containment

func contains(Bound) -> Bool

Returns a Boolean value indicating whether the given element is contained within the range.

func contains(where: (Bound) -> Bool) -> Bool

Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

func allSatisfy((Bound) -> Bool) -> Bool

Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.

Clamping a Range

func clamped(to: ClosedRange<Bound>) -> ClosedRange<Bound>

Returns a copy of this range clamped to the given limiting range.

Accessing Elements

var first: Bound?

The first element of the collection.

var last: Bound?

The last element of the collection.

subscript(ClosedRange<Bound>.Index) -> Bound

Accesses the element at specified position.

subscript<R>(R) -> Slice<ClosedRange<Bound>>

Accesses the contiguous subrange of the collection’s elements specified by a range expression.

subscript((UnboundedRange_) -> ()) -> Slice<ClosedRange<Bound>>
subscript(Range<ClosedRange<Bound>.Index>) -> Slice<ClosedRange<Bound>>

Accesses a contiguous subrange of the collection’s elements.

func randomElement() -> Bound?

Returns a random element of the collection.

func randomElement<T>(using: inout T) -> Bound?

Returns a random element of the collection, using the given generator as a source for randomness.

Finding Elements

func first(where: (Bound) -> Bool) -> Bound?

Returns the first element of the sequence that satisfies the given predicate.

func firstIndex(where: (Bound) -> Bool) -> Index?

Returns the first index in which an element of the collection satisfies the given predicate.

func last(where: (Bound) -> Bool) -> Bound?

Returns the last element of the sequence that satisfies the given predicate.

func lastIndex(where: (Bound) -> Bool) -> Index?

Returns the index of the last element in the collection that matches the given predicate.

func min(by: (Bound, Bound) -> Bool) -> Bound?

Returns the minimum element in the sequence, using the given predicate as the comparison between elements.

func max(by: (Bound, Bound) -> Bool) -> Bound?

Returns the maximum element in the sequence, using the given predicate as the comparison between elements.

Selecting Elements

func filter((Bound) -> Bool) -> [Bound]

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

func prefix(Int) -> Slice<ClosedRange<Bound>>

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

func prefix(through: Index) -> Slice<ClosedRange<Bound>>

Returns a subsequence from the start of the collection through the specified position.

func prefix(upTo: Index) -> Slice<ClosedRange<Bound>>

Returns a subsequence from the start of the collection up to, but not including, the specified position.

func prefix(while: (Bound) -> Bool) -> Slice<ClosedRange<Bound>>

Returns a subsequence containing the initial elements until predicate returns false and skipping the remaining elements.

func suffix(Int) -> Slice<ClosedRange<Bound>>

Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

func suffix(from: Index) -> Slice<ClosedRange<Bound>>

Returns a subsequence from the specified position to the end of the collection.

Excluding Elements

func drop(while: (Bound) -> Bool) -> Slice<ClosedRange<Bound>>

Returns a subsequence by skipping elements while predicate returns true and returning the remaining elements.

func dropFirst(Int) -> Slice<ClosedRange<Bound>>

Returns a subsequence containing all but the given number of initial elements.

func dropLast(Int) -> Slice<ClosedRange<Bound>>

Returns a subsequence containing all but the specified number of final elements.

Tranforming a Range's Elements

func map<T>((Bound) -> T) -> [T]

Returns an array containing the results of mapping the given closure over the sequence’s elements.

func compactMap<ElementOfResult>((Bound) -> ElementOfResult?) -> [ElementOfResult]

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

func flatMap<SegmentOfResult>((Bound) -> SegmentOfResult) -> [SegmentOfResult.Element]

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

func flatMap<ElementOfResult>((Bound) -> ElementOfResult?) -> [ElementOfResult]
Deprecated
func reduce<Result>(Result, (Result, Bound) -> Result) -> Result

Returns the result of combining the elements of the sequence using the given closure.

func reduce<Result>(into: Result, (inout Result, Bound) -> ()) -> Result

Returns the result of combining the elements of the sequence using the given closure.

var lazy: LazySequence<ClosedRange<Bound>>

A sequence containing the same elements as this sequence, but on which some operations, such as map and filter, are implemented lazily.

Iterating Over a Range's Elements

func forEach((Bound) -> Void)

Calls the given closure on each element in the sequence in the same order as a for-in loop.

func enumerated() -> EnumeratedSequence<ClosedRange<Bound>>

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

var underestimatedCount: Int

A value less than or equal to the number of elements in the sequence, calculated nondestructively.

var underestimatedCount: Int

A value less than or equal to the number of elements in the collection.

Reordering Elements

func sorted(by: (Bound, Bound) -> Bool) -> [Bound]

Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.

func reversed() -> ReversedCollection<ClosedRange<Bound>>

Returns a view presenting the elements of the collection in reverse order.

func shuffled() -> [Bound]

Returns the elements of the sequence, shuffled.

func shuffled<T>(using: inout T) -> [Bound]

Returns the elements of the sequence, shuffled using the given generator as a source for randomness.

Splitting and Joining Elements

func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator: (Bound) -> Bool) -> [Slice<ClosedRange<Bound>>]

Returns the longest possible subsequences of the collection, in order, that don’t contain elements satisfying the given predicate.

Comparing Ranges

static func == (ClosedRange<Bound>, ClosedRange<Bound>) -> Bool

Returns a Boolean value indicating whether two ranges are equal.

static func != (ClosedRange<Bound>, ClosedRange<Bound>) -> Bool

Returns a Boolean value indicating whether two values are not equal.

func overlaps(Range<Bound>) -> Bool

Returns a Boolean value indicating whether this range and the given range contain an element in common.

func overlaps(ClosedRange<Bound>) -> Bool

Returns a Boolean value indicating whether this range and the given range contain an element in common.

Comparing Ranges as Collections

func elementsEqual<OtherSequence>(OtherSequence, by: (Bound, OtherSequence.Element) -> Bool) -> Bool

Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements in the same order, using the given predicate as the equivalence test.

func lexicographicallyPrecedes<OtherSequence>(OtherSequence, by: (Bound, Bound) -> Bool) -> Bool

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.

func starts<PossiblePrefix>(with: PossiblePrefix, by: (Bound, PossiblePrefix.Element) -> Bool) -> Bool

Returns a Boolean value indicating whether the initial elements of the sequence are equivalent to the elements in another sequence, using the given predicate as the equivalence test.

Manipulating Indices

var startIndex: ClosedRange<Bound>.Index

The position of the first element in the range.

var endIndex: ClosedRange<Bound>.Index

The range’s “past the end” position—that is, the position one greater than the last valid subscript argument.

func index(after: ClosedRange<Bound>.Index) -> ClosedRange<Bound>.Index

Returns the position immediately after the given index.

func formIndex(after: inout Index)

Replaces the given index with its successor.

func index(before: ClosedRange<Bound>.Index) -> ClosedRange<Bound>.Index

Returns the position immediately before the given index.

func formIndex(before: inout Index)

Replaces the given index with its predecessor.

func index(ClosedRange<Bound>.Index, offsetBy: Int) -> ClosedRange<Bound>.Index

Returns an index that is the specified distance from the given index.

func formIndex(inout Index, offsetBy: Int)

Offsets the given index by the specified distance.

func index(Index, offsetBy: Int, limitedBy: Index) -> Index?

Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.

func formIndex(inout Index, offsetBy: Int, limitedBy: Index) -> Bool

Offsets the given index by the specified distance, or so that it equals the given limiting index.

func distance(from: ClosedRange<Bound>.Index, to: ClosedRange<Bound>.Index) -> Int

Returns the distance between two indices.

func hash(into: inout Hasher)

Hashes the essential components of this value by feeding them into the given hasher.

Describing a Range

var description: String

A textual representation of the range.

var debugDescription: String

A textual representation of the range, suitable for debugging.

var customMirror: Mirror

The custom mirror for this instance.

Encoding and Decoding a Range

func encode(to: Encoder)

Encodes this value into the given encoder.

init(from: Decoder)

Creates a new instance by decoding from the given decoder.

Infrequently Used Functionality

func withContiguousStorageIfAvailable<R>((UnsafeBufferPointer<Bound>) -> R) -> R?

Call body(p), where p is a pointer to the collection’s contiguous storage. If no such storage exists, it is first created. If the collection does not support an internal representation in a form of contiguous storage, body is not called and nil is returned.

init(uncheckedBounds: (lower: Bound, upper: Bound))

Creates an instance with the given bounds.

Supporting Types

enum ClosedRange.Index

A type that represents a position in the collection.

typealias ClosedRange.Element

A type representing the sequence’s elements.

typealias ClosedRange.Iterator

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

typealias ClosedRange.SubSequence

A sequence that represents a contiguous subrange of the collection’s elements.

Type Aliases

typealias ClosedRange.Indices

A type that represents the indices that are valid for subscripting the collection, in ascending order.

Instance Properties

var hashValue: Int

The hash value.

Instance Methods

func difference<C>(from: C, by: (C.Element, Bound) -> Bool) -> CollectionDifference<Bound>

Returns the difference needed to produce this collection’s ordered elements from the given collection, using the given predicate as an equivalence test.

func index(where: (Bound) -> Bool) -> Index?

Returns the first index in which an element of the collection satisfies the given predicate.

Deprecated

Relationships

Conforms To

See Also

Ranges

static func ..< (Self, Self) -> Range<Self>

Returns a half-open range that contains its lower bound but not its upper bound.

struct Range

A half-open interval from a lower bound up to, but not including, an upper bound.

static func ... (Self, Self) -> ClosedRange<Self>

Returns a closed range that contains both of its bounds.