ReversedCollection.Index

struct ReversedCollection.Index

An index that traverses the same positions as an underlying index, with inverted traversal direction.

Inheritance Comparable, Equatable, Hashable View Protocol Hierarchy →
Import import Swift

Initializers

init(_:)

Creates a new index into a reversed collection for the position before the specified index.

When you create an index into a reversed collection using base, an index from the underlying collection, the resulting index is the position of the element before the element referenced by base. The following example creates a new ReversedIndex from the index of the "a" character in a string's character view.

let name = "Horatio"
let aIndex = name.firstIndex(of: "a")!
// name[aIndex] == "a"

let reversedName = name.reversed()
let i = ReversedIndex<String>(aIndex)
// reversedName[i] == "r"

The element at the position created using ReversedIndex<...>(aIndex) is "r", the character before "a" in the name string.

base: The position after the element to create an index for.

Declaration

init(_ base: Base.Index)

Instance Variables

var base: Base.Index

The position after this position in the underlying collection.

To find the position that corresponds with this index in the original, underlying collection, use that collection's index(before:) method with the base property.

The following example declares a function that returns the index of the last even number in the passed array, if one is found. First, the function finds the position of the last even number as a ReversedIndex in a reversed view of the array of numbers. Next, the function calls the array's index(before:) method to return the correct position in the passed array.

func indexOfLastEven(_ numbers: [Int]) -> Int? {
    let reversedNumbers = numbers.reversed()
    guard let i = reversedNumbers.firstIndex(where: { $0 % 2 == 0 })
        else { return nil }

    return numbers.index(before: i.base)
}

let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
if let lastEven = indexOfLastEven(numbers) {
    print("Last even number: \(numbers[lastEven])")
}
// Prints "Last even number: 40"

Declaration

var base: Base.Index { get }
var hashValue: Int

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

hasher: The hasher to use when combining the components of this instance.

Declaration

var hashValue: Int { get }

Instance Methods

func hash(into:)

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

Implement this method to conform to the Hashable protocol. The components used for hashing must be the same as the components compared in your type's == operator implementation. Call hasher.combine(_:) with each of these components.

Important: Never call finalize() on hasher. Doing so may become a compile-time error in the future.

hasher: The hasher to use when combining the components of this instance.

Declaration

func hash(into hasher: inout Hasher)