Last active
June 28, 2017 10:08
-
-
Save natecook1000/b6be8929451bb6f35ad4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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