Skip to content

Instantly share code, notes, and snippets.

@erica
Last active September 1, 2015 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/a2ba42d995f52340e8dd to your computer and use it in GitHub Desktop.
Save erica/a2ba42d995f52340e8dd to your computer and use it in GitHub Desktop.
let array = "abcdefghijklmnop".characters.map({String($0)})
let range = 5..<array.count
extension ArraySlice {
func slicenumerate() -> Zip2Sequence<Range<Int>, ArraySlice<Element>> {
// slice.indices gleefully stolen from Mike Ash, originally startIndex..<endIndex
return zip(self.indices, self)
}
func forEachWithIndex(@noescape closure: (Int, Generator.Element) -> Void) {
// thanks, https://twitter.com/publicfarley/status/630091086971699202
// (via http://twitter.com/oisdk/status/638809052332617728)
self.slicenumerate().forEach{ closure($0.0, $0.1) }
}
}
let slice = array[range]
for (index, value) in slice.slicenumerate() {
print(index, value)
}
slice.forEachWithIndex {
index, value in
print(index, value)
}
// Or just do this:
// https://gist.github.com/natecook1000/b6be8929451bb6f35ad4
// Thanks, Nate Cook
extension CollectionType {
/// Return a lazy SequenceType containing pairs *(i, x)*,
/// where *i*s are the sequential indices and *x*s are the elements of `base`.
func enumerateWithIndex() -> AnySequence<(Index, Generator.Element)> {
return AnySequence(zip(indices, self))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment