AnyBidirectionalCollection

struct AnyBidirectionalCollection

A type-erased wrapper over any collection with indices that support bidirectional traversal.

Inheritance BidirectionalCollection
Associated Types
public typealias Indices = DefaultIndices<AnyBidirectionalCollection<Element>>
public typealias Iterator = AnyIterator<Element>

By default, a collection conforms to the Sequence protocol by supplying IndexingIterator as its associated Iterator type.

public typealias Index = AnyIndex

Valid indices consist of the position of every element and a "past the end" position that's not valid for use as a subscript argument.

public typealias SubSequence = AnyBidirectionalCollection<Element>

This associated type appears as a requirement in the Sequence protocol, but it is restated here with stricter constraints. In a collection, the subsequence should also conform to Collection.

An AnyBidirectionalCollection instance forwards its operations to a base collection having the same Element type, hiding the specifics of the underlying collection.

Initializers

init init(_:) Required

Creates a type-erased collection that wraps the given collection.

  • Parameter base: The collection to wrap.

Complexity: O(1).

Declaration

@inlinable public init<C>(_ base: C) where Element == C.Element, C: BidirectionalCollection
init init(_:) Required

Creates an AnyBidirectionalCollection having the same underlying collection as other.

Complexity: O(1)

Declaration

@inlinable public init(_ other: AnyBidirectionalCollection<Element>)
init init(_:) Required

Creates a type-erased collection that wraps the given collection.

  • Parameter base: The collection to wrap.

Complexity: O(1).

Declaration

@inlinable public init<C>(_ base: C) where Element == C.Element, C: RandomAccessCollection
init init(_:) Required

Creates an AnyBidirectionalCollection having the same underlying collection as other.

Complexity: O(1)

Declaration

@inlinable public init(_ other: AnyRandomAccessCollection<Element>)
init init?(_:) Required

Creates an AnyBidirectionalCollection having the same underlying collection as other.

If the underlying collection stored by other does not satisfy BidirectionalCollection, the result is nil.

Complexity: O(1)

Declaration

@inlinable public init?(_ other: AnyCollection<Element>)

Instance Variables

var count Required

The number of elements.

To check whether a collection is empty, use its isEmpty property instead of comparing count to zero. Calculating count can be an O(n) operation.

Complexity: O(n)

Declaration

var count: Int
var endIndex Required

The collection's "past the end" position---that is, the position one greater than the last valid subscript argument.

endIndex is always reachable from startIndex by zero or more applications of index(after:).

Declaration

var endIndex: AnyBidirectionalCollection<Element>.Index
var last Required

The last element of the collection.

If the collection is empty, the value of this property is nil.

let numbers = [10, 20, 30, 40, 50]
if let lastNumber = numbers.last {
    print(lastNumber)
}
// Prints "50"

Complexity: O(1)

Declaration

var last: Self.Element?
var startIndex Required

The position of the first element in a non-empty collection.

In an empty collection, startIndex == endIndex.

Declaration

var startIndex: AnyBidirectionalCollection<Element>.Index
var underestimatedCount Required

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

The default implementation returns 0. If you provide your own implementation, make sure to compute the value nondestructively.

Complexity: O(1), except if the sequence also conforms to Collection. In this case, see the documentation of Collection.underestimatedCount.

Declaration

var underestimatedCount: Int

Subscripts

subscript subscript(bounds:) Required

Accesses a contiguous subrange of the collection's elements.

The accessed slice uses the same indices for the same elements as the original collection uses. Always use the slice's startIndex property instead of assuming that its indices start at a particular value.

This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array.

let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2 ..< streets.endIndex]
print(streetsSlice)
// Prints "["Channing", "Douglas", "Evarts"]"

let index = streetsSlice.firstIndex(of: "Evarts")    // 4
print(streets[index!])
// Prints "Evarts"
  • Parameter bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Complexity: O(1)

Declaration

@inlinable public subscript(bounds: Range<AnyBidirectionalCollection<Element>.Index>) -> AnyBidirectionalCollection<Element>.SubSequence
subscript subscript(position:) Required

Accesses the element indicated by position.

Precondition: position indicates a valid position in self and position != endIndex.

Declaration

@inlinable public subscript(position: AnyBidirectionalCollection<Element>.Index) -> Element

Instance Methods

func difference(from other: C, by areEquivalent: (C.Element, Self.Element) -> Bool) -> CollectionDifference<Self.Element> Required

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

This function does not infer element moves. If you need to infer moves, call the inferringMoves() method on the resulting difference.

Complexity: Worst case performance is O(n * m), where n is the count of this collection and m is other.count. You can expect faster execution when the collections share many common elements.

Declaration

@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func difference<C>(from other: C, by areEquivalent: (C.Element, Self.Element) -> Bool) -> CollectionDifference<Self.Element> where C: BidirectionalCollection, Self.Element == C.Element
func distance(from start: Self.Index, to end: Self.Index) -> Int Required

Declaration

@inlinable public func distance(from start: Self.Index, to end: Self.Index) -> Int
func distance(from start: AnyBidirectionalCollection<Element>.Index, to end: AnyBidirectionalCollection<Element>.Index) -> Int Required

Returns the distance between two indices.

Unless the collection conforms to the BidirectionalCollection protocol, start must be less than or equal to end.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the resulting distance.

Declaration

@inlinable public func distance(from start: AnyBidirectionalCollection<Element>.Index, to end: AnyBidirectionalCollection<Element>.Index) -> Int
func drop(while predicate: (Element) throws -> Bool) rethrows -> AnyBidirectionalCollection<Element> Required

Declaration

@inlinable public func drop(while predicate: (Element) throws -> Bool) rethrows -> AnyBidirectionalCollection<Element>
func dropFirst(_ n: Int = 1) -> AnyBidirectionalCollection<Element> Required

Declaration

@inlinable public func dropFirst(_ n: Int = 1) -> AnyBidirectionalCollection<Element>
func dropLast(_ n: Int = 1) -> AnyBidirectionalCollection<Element> Required

Declaration

@inlinable public func dropLast(_ n: Int = 1) -> AnyBidirectionalCollection<Element>
func dropLast(_ k: Int) -> Self.SubSequence Required

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

If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"
  • Parameter k: The number of elements to drop off the end of the collection. k must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to drop.

Declaration

@inlinable public func dropLast(_ k: Int) -> Self.SubSequence
func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element] Required

Declaration

@inlinable public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]
func forEach(_ body: (Element) throws -> Void) rethrows Required

Declaration

@inlinable public func forEach(_ body: (Element) throws -> Void) rethrows
func formIndex(_ i: inout AnyBidirectionalCollection<Element>.Index, offsetBy n: Int) Required

Declaration

@inlinable public func formIndex(_ i: inout AnyBidirectionalCollection<Element>.Index, offsetBy n: Int)
func formIndex(_ i: inout AnyBidirectionalCollection<Element>.Index, offsetBy n: Int, limitedBy limit: AnyBidirectionalCollection<Element>.Index) -> Bool Required

Declaration

@inlinable public func formIndex(_ i: inout AnyBidirectionalCollection<Element>.Index, offsetBy n: Int, limitedBy limit: AnyBidirectionalCollection<Element>.Index) -> Bool
func formIndex(after i: inout AnyBidirectionalCollection<Element>.Index) Required

Replaces the given index with its successor.

  • Parameter i: A valid index of the collection. i must be less than endIndex.

Declaration

@inlinable public func formIndex(after i: inout AnyBidirectionalCollection<Element>.Index)
func formIndex(before i: inout Self.Index) Required

Replaces the given index with its predecessor.

  • Parameter i: A valid index of the collection. i must be greater than startIndex.

Declaration

@inlinable public func formIndex(before i: inout Self.Index)
func formIndex(before i: inout AnyBidirectionalCollection<Element>.Index) Required

Replaces the given index with its predecessor.

  • Parameter i: A valid index of the collection. i must be greater than startIndex.

Declaration

@inlinable public func formIndex(before i: inout AnyBidirectionalCollection<Element>.Index)
func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index Required

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index
func index(_ i: AnyBidirectionalCollection<Element>.Index, offsetBy n: Int) -> AnyBidirectionalCollection<Element>.Index Required

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

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position.

let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 4)
print(s[i])
// Prints "t"

The value passed as distance must not offset i beyond the bounds of the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: AnyBidirectionalCollection<Element>.Index, offsetBy n: Int) -> AnyBidirectionalCollection<Element>.Index
func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index? Required

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index?
func index(_ i: AnyBidirectionalCollection<Element>.Index, offsetBy n: Int, limitedBy limit: AnyBidirectionalCollection<Element>.Index) -> AnyBidirectionalCollection<Element>.Index? Required

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

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position. The operation doesn't require going beyond the limiting s.endIndex value, so it succeeds.

let s = "Swift"
if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
    print(s[i])
}
// Prints "t"

The next example attempts to retrieve an index six positions from s.startIndex but fails, because that distance is beyond the index passed as limit.

let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
print(j)
// Prints "nil"

The value passed as distance must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: AnyBidirectionalCollection<Element>.Index, offsetBy n: Int, limitedBy limit: AnyBidirectionalCollection<Element>.Index) -> AnyBidirectionalCollection<Element>.Index?
func index(after i: AnyBidirectionalCollection<Element>.Index) -> AnyBidirectionalCollection<Element>.Index Required

Returns the position immediately after the given index.

The successor of an index must be well defined. For an index i into a collection c, calling c.index(after: i) returns the same index every time.

  • Parameter i: A valid index of the collection. i must be less than endIndex.

Declaration

@inlinable public func index(after i: AnyBidirectionalCollection<Element>.Index) -> AnyBidirectionalCollection<Element>.Index
func index(before i: AnyBidirectionalCollection<Element>.Index) -> AnyBidirectionalCollection<Element>.Index Required

Returns the position immediately before the given index.

  • Parameter i: A valid index of the collection. i must be greater than startIndex.

Declaration

@inlinable public func index(before i: AnyBidirectionalCollection<Element>.Index) -> AnyBidirectionalCollection<Element>.Index
func last(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element? Required

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

This example uses the last(where:) method to find the last negative number in an array of integers:

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let lastNegative = numbers.last(where: { $0 < 0 }) {
    print("The last negative number is \(lastNegative).")
}
// Prints "The last negative number is -6."
  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func last(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element?
func lastIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index? Required

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

You can use the predicate to find an element of a type that doesn't conform to the Equatable protocol or to find an element that matches particular criteria. This example finds the index of the last name that begins with the letter A:

let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.lastIndex(where: { $0.hasPrefix("A") }) {
    print("\(students[i]) starts with 'A'!")
}
// Prints "Akosua starts with 'A'!"
  • Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func lastIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?
func makeIterator() -> AnyBidirectionalCollection<Element>.Iterator Required

Returns an iterator over the elements of this collection.

Declaration

@inlinable public func makeIterator() -> AnyBidirectionalCollection<Element>.Iterator
func map(_ transform: (Element) throws -> T) rethrows -> [T] Required

Declaration

@inlinable public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
func prefix(_ maxLength: Int = 1) -> AnyBidirectionalCollection<Element> Required

Declaration

@inlinable public func prefix(_ maxLength: Int = 1) -> AnyBidirectionalCollection<Element>
func prefix(while predicate: (Element) throws -> Bool) rethrows -> AnyBidirectionalCollection<Element> Required

Declaration

@inlinable public func prefix(while predicate: (Element) throws -> Bool) rethrows -> AnyBidirectionalCollection<Element>
func reversed() -> ReversedCollection<Self> Required

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

You can reverse a collection without allocating new space for its elements by calling this reversed() method. A ReversedCollection instance wraps an underlying collection and provides access to its elements in reverse order. This example prints the characters of a string in reverse order:

let word = "Backwards"
for char in word.reversed() {
    print(char, terminator: "")
}
// Prints "sdrawkcaB"

If you need a reversed collection of the same type, you may be able to use the collection's sequence-based or collection-based initializer. For example, to get the reversed version of a string, reverse its characters and initialize a new String instance from the result.

let reversedWord = String(word.reversed())
print(reversedWord)
// Prints "sdrawkcaB"

Complexity: O(1)

Declaration

@inlinable public func reversed() -> ReversedCollection<Self>
func suffix(_ maxLength: Int) -> AnyBidirectionalCollection<Element> Required

Declaration

@inlinable public func suffix(_ maxLength: Int) -> AnyBidirectionalCollection<Element>
func suffix(_ maxLength: Int) -> Self.SubSequence Required

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

If the maximum length exceeds the number of elements in the collection, the result contains the entire collection.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is equal to maxLength.

Declaration

@inlinable public func suffix(_ maxLength: Int) -> Self.SubSequence