Skip to content

Instantly share code, notes, and snippets.

@tadpol
Last active June 2, 2016 14:35
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 tadpol/ad119494c8ea86d9aeeaea3479eee016 to your computer and use it in GitHub Desktop.
Save tadpol/ad119494c8ea86d9aeeaea3479eee016 to your computer and use it in GitHub Desktop.
/* My first attempt at building a sequence that will make a collection loop forever.
I had a need where I wanted to loop over two lists but instead of truncating the
longer list to the shorter one, I wanted the shorter one repeat until the longer
one completed.
FE:
let c = ["Z", "Y", "X", "W", "V", "U", "T"]
let d = [0,9,7]
let i = ForeverSequence(vals: d)
for (k,l) in zip(c,i) {
print("\(k) - \(l)")
}
*/
struct ForeverSequence<C : CollectionType> : SequenceType {
let vals: C
func generate() -> AnyGenerator<C.Generator.Element> {
guard vals.count > 0 else {
return AnyGenerator { nil }
}
var gen = vals.generate()
return AnyGenerator<C.Generator.Element> {
if let r = gen.next() {
return r
} else {
// at end, start over.
gen = self.vals.generate() // reset generator
return gen.next()! // From the guard above, we know that there is atleast one element here.
}
}
}
}
@tadpol
Copy link
Author

tadpol commented Jun 2, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment