Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A new Sequence type that returns a repeating sequence of values.
/// The RepeatingSequence accepts a collection and returns the values sequentially until the
/// final element is returned, at which point the sequence wraps around to the first element
/// of the collection and continues from there.
struct RepeatingSequence<T>: Sequence {
/// The Collection that we base our sequence on. We use a Collection and not
/// another Sequence because Sequences are not guaranteed to be repeatedly iterated.
let data: AnyCollection<T>
/// We can optionally specify a maximum number of iterations. This is necessary
/// to create non-infinite Sequences.
let maxCount: Int?
func makeIterator() -> AnyIterator<T> {
var index: AnyCollection.Index = data.startIndex
var count: Int = 0
return AnyIterator<T> {
if let max = self.maxCount, count >= max {
return nil
defer {
index = index)
if index == {
index =
count += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment