How to enumerate a slice using the original indices?

我们两清 提交于 2019-12-04 04:52:13

enumerate() returns a sequence of (n, elem) pairs, where the ns are consecutive Ints starting at zero. This makes sense because it is a protocol extension method for SequenceType, and an arbitrary sequence does not necessarily have index associated with the elements.

You would get your expected result with

let powersSlice = slice.indices.map { pow(slice[$0], Double($0)) }

or

let powersSlice = zip(slice.indices, slice).map { pow($1, Double($0)) }

The latter approach could be generalized to a protocol extension method for arbitrary collections:

extension CollectionType {
    func indexEnumerate() -> AnySequence<(index: Index, element: Generator.Element)> {
        return AnySequence(zip(indices, self))
    }
}

This returns a sequence of (index, elem) pairs where index is an index of the collection and elem the corresponding element. AnySequence is used to "hide" the specific type Zip2Sequence<RangeGenerator<Self.Index>, Self> returned from zip() from the caller.

Example:

let powersSliceEnumerate = slice.indexEnumerate().map() { pow($0.element, Double($0.index)) }
print("powersSliceEnumerate == \(powersSliceEnumerate)")
// powersSliceEnumerate == [2.0, 9.0]

Update for Swift 3:

extension Collection {
    func indexEnumerate() -> AnySequence<(Indices.Iterator.Element, Iterator.Element)> {
        return AnySequence(zip(indices, self))
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!