Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
each_cons from Ruby in Swift as a function on Sequence
extension Collection {
func eachConsecutive(_ size: Int) -> Array<SubSequence> {
let droppedIndices = indices.dropFirst(size - 1)
return zip(indices, droppedIndices)
.map { return self[$0...$1] }
extension Sequence where SubSequence: Sequence, SubSequence.Iterator.Element == Iterator.Element {
func eachPair() -> AnySequence<(Iterator.Element, Iterator.Element)> {
return AnySequence(zip(self, self.dropFirst()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment