Generic Structure

Range

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

Declaration

struct Range<Bound> where Bound : Comparable

Overview

You create a Range instance by using the half-open range operator (..<).

let underFive = 0.0..<5.0

You can use a Range instance to quickly check if a value is contained in a particular range of values. For example:

underFive.contains(3.14)
// true
underFive.contains(6.28)
// false
underFive.contains(5.0)
// false

Range instances can represent an empty interval, unlike ClosedRange.

let empty = 0.0..<0.0
empty.contains(0.0)
// false
empty.isEmpty
// true

Using a Range as a Collection of Consecutive Values

When a 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, but not including, its upper bound.

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

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:to:by:) function.

Topics

Creating a Range

Create a new range using the half-open range operator (..<).

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

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

Converting Ranges

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

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

init(ClosedRange<Bound>)

Creates an instance equivalent to the given ClosedRange.

init?(NSRange, in: String)

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.

static func ~= (Range<Bound>, Bound) -> Bool

Returns a Boolean value indicating whether a value is included in a range.

Clamping a Range

func clamped(to: Range<Bound>) -> Range<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(Range<Bound>.Index) -> Range<Bound>.Element

Accesses the element at specified position.

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

Accesses the subsequence bounded by the given range.

subscript<R>(R) -> Range<Bound>

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

subscript((UnboundedRange_) -> ()) -> Range<Bound>
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(of: Bound) -> Bound?

Returns the first index where the specified value appears in the collection.

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

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(of: Bound) -> Bound?

Returns the last index where the specified value appears in the collection.

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

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

func min() -> Bound?

Returns the minimum element in the sequence.

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() -> Bound?

Returns the maximum element in the sequence.

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

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

Working with Foundation Ranges

init?(NSRange)
init?(NSRange)

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) -> Range<Bound>

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

func prefix(through: Bound) -> Range<Bound>

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

func prefix(upTo: Bound) -> Range<Bound>

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

func prefix(while: (Bound) -> Bool) -> Range<Bound>

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

func suffix(Int) -> Range<Bound>

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

func suffix(from: Bound) -> Range<Bound>

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

Excluding Elements

func dropFirst(Int) -> Range<Bound>

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

func dropLast(Int) -> Range<Bound>

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

func drop(while: (Bound) -> Bool) -> Range<Bound>

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

func popFirst() -> Bound?

Removes and returns the first element of the collection.

func popLast() -> Bound?

Removes and returns the last element of the collection.

func removeFirst() -> Bound

Removes and returns the first element of the collection.

func removeFirst(Int)

Removes the specified number of elements from the beginning of the collection.

func removeLast() -> Bound

Removes and returns the last element of the collection.

func removeLast(Int)

Removes the given number of elements from the end of the collection.

Transforming 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<Range<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<Range<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.

func makeIterator() -> IndexingIterator<Range<Bound>>

Returns an iterator over the elements of the collection.

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() -> [Bound]

Returns the elements of the sequence, sorted.

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<Range<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(separator: Bound, maxSplits: Int, omittingEmptySubsequences: Bool) -> [Range<Bound>]

Returns the longest possible subsequences of the collection, in order, around elements equal to the given element.

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

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

func joined() -> FlattenSequence<Range<Bound>>

Returns the elements of this sequence of sequences, concatenated.

func joined<Separator>(separator: Separator) -> JoinedSequence<Range<Bound>>

Returns the concatenated elements of this sequence of sequences, inserting the given separator between each element.

func joined(separator: String) -> String

Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.

func joined(separator: String) -> String

Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.

Comparing Ranges

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

Returns a Boolean value indicating whether two ranges are equal.

static func != (Range<Bound>, Range<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) -> Bool

Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.

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) -> Bool

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (<) to compare elements.

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) -> Bool

Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.

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: Bound
var endIndex: Bound
var indices: Range<Bound>

The indices that are valid for subscripting the collection, in ascending order.

var indices: Range<Bound>

The indices that are valid for subscripting the range, in ascending order.

func index(after: Range<Bound>.Index) -> Range<Bound>.Index
func formIndex(after: inout Bound)

Replaces the given index with its successor.

func index(before: Range<Bound>.Index) -> Range<Bound>.Index
func formIndex(before: inout Bound)

Replaces the given index with its predecessor.

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

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

func formIndex(inout Bound, offsetBy: Int)

Offsets the given index by the specified distance.

func index(Range<Bound>.Index, offsetBy: Int) -> Range<Bound>.Index
func formIndex(inout Bound, offsetBy: Int, limitedBy: Bound) -> Bool

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

func distance(from: Range<Bound>.Index, to: Range<Bound>.Index) -> Int
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.

Encoding and Decoding a Range

func encode(to: Encoder)
init(from: Decoder)

Infrequently Used Functionality

func index(of: Bound) -> Bound?

Returns the first index where the specified value appears in the collection.

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

Creates an instance with the given bounds.

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

Supporting Types

typealias Range.Element
typealias Range.Index

A type that represents a position in the range.

typealias Range.Indices
typealias Range.Iterator
typealias Range.SubSequence

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.

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

Returns a closed range that contains both of its bounds.

struct ClosedRange

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