Files
swift-algorithms/Guides/Indexed.md
T
Daniel Tull 93c8724c72 Add conformances to LazySequenceProtocol and LazyCollectionProtocol (#47)
* Conform Intersperse to LazySequenceProtocol when the base sequence does

* Add conformance to LazyCollectionProtocol

* Conform Indexed to LazyCollectionProtocol when Base conforms

* Rename XCTAssertLazy to XCTAssertLazySequence

* Add XCTAssertLazyCollection

* Add lazy test for Intersperse

* Update Indexed guide

* Add lazy conformances to SlidingWindows

* Update SlidingWindows guide
2020-12-01 15:47:13 -06:00

959 B

Indexed

[Source | Tests]

The enumerated method, but pairing each element with its index instead of an incrementing integer counter.

This is essentially equivalent to zip(x.indices, x):

let numbers = [10, 20, 30, 40, 50]
var matchingIndices: Set<Int> = []
for (i, n) in numbers.indexed() {
    if n.isMultiple(of: 20) { 
        matchingIndices.insert(i) 
    }
}
// matchingIndices == [1, 3]

Detailed Design

The indexed method returns an Indexed type:

extension Collection {
    func indexed() -> Indexed<Self>
}

Indexed scales from a collection up to a random-access collection, depending on its base type. Indexed also conforms to LazySequenceProtocol and LazyCollectionProtocol when the base type conforms.