mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-25 04:27:47 +00:00
* Rename types to include a Sequence or Collection suffix, and clean up some guides * Various refactors * Replace `validateIndexTraversals` test method with `IndexValidator` type * Add LazySequenceProtocol to StridingSequence, StridingCollection * Update the Numerics dependency to 1.0 * Set `IndexedCollection.Indices` to `Base.Indices` * Remove deprecations * Update the changelog/README for the 1.0.0 release * Fix compiler error on Linux * Rename `WindowsCollection` to `WindowsOfCountCollection`
36 lines
960 B
Markdown
36 lines
960 B
Markdown
# Indexed
|
|
|
|
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Indexed.swift) |
|
|
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/IndexedTests.swift)]
|
|
|
|
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)`:
|
|
|
|
```swift
|
|
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 `IndexedCollection` type:
|
|
|
|
```swift
|
|
extension Collection {
|
|
func indexed() -> IndexedCollection<Self>
|
|
}
|
|
```
|
|
|
|
`IndexedCollection` scales from a collection up to a random-access collection,
|
|
depending on its base type. `Indexed` also conforms to `LazySequenceProtocol`
|
|
when the base type conforms.
|
|
|