Protocol

RandomAccessCollection

A collection that supports efficient random-access index traversal.

Overview

Random-access collections can move indices any distance and measure the distance between indices in O(1) time. Therefore, the fundamental difference between random-access and bidirectional collections is that operations that depend on index movement or distance measurement offer significantly improved efficiency. For example, a random-access collection’s count property is calculated in O(1) instead of requiring iteration of an entire collection.

Conforming to the RandomAccessCollection Protocol

The RandomAccessCollection protocol adds further constraints on the associated Indices and SubSequence types, but otherwise imposes no additional requirements over the BidirectionalCollection protocol. However, in order to meet the complexity guarantees of a random-access collection, either the index for your custom type must conform to the Strideable protocol or you must implement the index(_:offsetBy:) and distance(from:to:) methods with O(1) efficiency.

Protocol Requirements

Associated Types

Indices

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

SubSequence

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

Instance Properties

var indices: Self.Indices

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

Subscripts

subscript(Range<Self.Index>)

Accesses a contiguous subrange of the collection’s elements.

Default Implementations

Instance Properties

var indices: CountableRange<Self.Index>

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

var indices: DefaultRandomAccessIndices<Self>

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

var lazy: LazyRandomAccessCollection<Self>

A view onto this collection that provides lazy implementations of normally eager operations, such as map and filter.

var lazy: Self

Identical to self.

Instance Methods

func distance(from: Self.Index, to: Self.Index)

Returns the distance between two indices.

func index(Self.Index, offsetBy: Self.Index.Stride)

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

func index(after: Self.Index)

Returns the position immediately after the given index.

func index(before: Self.Index)

Returns the position immediately after the given index.

func reversed()

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

Subscripts

subscript(Range<Self.Index>)

Accesses a contiguous subrange of the collection’s elements.