Last active
June 2, 2016 14:35
-
-
Save tadpol/ad119494c8ea86d9aeeaea3479eee016 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
/* 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. | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used ideas from @kevlario (see http://swiftlang.ng.bluemix.net/#/repl/38e113adcb713529895a4ed9360c5a169dd965ebf68784d4d520781231129bb9 )