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 = self.data.index(after: index) | |
if index == self.data.endIndex { | |
index = self.data.startIndex | |
} | |
count += 1 | |
} | |
return self.data[index] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment