Skip to content

Instantly share code, notes, and snippets.

@hsavit1
Forked from neilpa/iterate.swift
Created December 16, 2015 02:31
Show Gist options
  • Select an option

  • Save hsavit1/0dddb4fe1ebe2cc55225 to your computer and use it in GitHub Desktop.

Select an option

Save hsavit1/0dddb4fe1ebe2cc55225 to your computer and use it in GitHub Desktop.
// Similar to `enumerate` but provides the collection's index type
// rather than an Int for the position
public func iterate<C: CollectionType>(collection: C) -> SequenceOf<(C.Index, C.Generator.Element)> {
var index = collection.startIndex
// type-inference doesn't want to work without this
return SequenceOf { _ -> GeneratorOf<(C.Index, C.Generator.Element)> in
return GeneratorOf {
if index == collection.endIndex {
return nil
}
let previous = index++
return (previous, collection[previous])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment