Protocol

BidirectionalCollection

A collection that supports backward as well as forward traversal.

Overview

Bidirectional collections offer traversal backward from any valid index, not including a collection’s startIndex. Bidirectional collections can therefore offer additional operations, such as a last property that provides efficient access to the last element and a reversed() method that presents the elements in reverse order. In addition, bidirectional collections have more efficient implementations of some sequence and collection methods, such as suffix(_:).

Conforming to the BidirectionalCollection Protocol

To add BidirectionalProtocol conformance to your custom types, implement the index(before:) method in addition to the requirements of the Collection protocol.

Indices that are moved forward and backward in a bidirectional collection move by the same amount in each direction. That is, for any index i into a bidirectional collection c:

  • If i >= c.startIndex && i < c.endIndex, c.index(before: c.index(after: i)) == i.

  • If i > c.startIndex && i <= c.endIndex c.index(after: c.index(before: i)) == i.

Protocol Requirements

Associated Types

Indices

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

SubSequence

A sequence that can represent 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.

var last: Self.Iterator.Element?

The last element of the collection.

Instance Methods

func formIndex(before: inout Self.Index)

Replaces the given index with its predecessor.

func index(before: Self.Index)

Returns the position immediately before the given index.

Subscripts

subscript(Range<Self.Index>)

Accesses a contiguous subrange of the collection’s elements.

Default Implementations

Instance Properties

var indices: DefaultBidirectionalIndices<Self>

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

var last: Self.Iterator.Element?

The last element of the collection.

var lazy: LazyBidirectionalCollection<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 dropLast(Int)

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

func joined()

Returns the elements of this collection of collections, concatenated.

func popLast()

Removes and returns the last element of the collection.

func removeLast()

Removes and returns the last element of the collection.

func removeLast(Int)

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

func reversed()

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

func suffix(Int)

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