Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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