Skip to content

Instantly share code, notes, and snippets.

@zyg-github
Forked from natecook1000/enumerateWithIndex.swift
Created February 23, 2016 01:18
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 zyg-github/c83904e37bb68269e4d9 to your computer and use it in GitHub Desktop.
Save zyg-github/c83904e37bb68269e4d9 to your computer and use it in GitHub Desktop.
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)> {
var index = startIndex
return AnySequence {
return anyGenerator {
guard index != self.endIndex else { return nil }
return (index, self[index++])
}
}
}
}
let str = "Hello from Nate"
// omg
let name = str.characters[str.characters.startIndex.advancedBy(11) ..< str.characters.startIndex.advancedBy(15)]
for (index, char) in name.enumerate() {
// type doesn't match:
// error: cannot subscript a value of type 'String.CharacterView' with an index of type 'Int'
// print(char, name[index])
}
for (index, char) in name.enumerateWithIndex() {
print(char, name[index])
}
// N N
// a a
// t t
// e e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment