Skip to content

Instantly share code, notes, and snippets.

@JoshuaSullivan
Created December 8, 2016 15:49
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 JoshuaSullivan/be8e02b9ad7a03377075791e36160610 to your computer and use it in GitHub Desktop.
Save JoshuaSullivan/be8e02b9ad7a03377075791e36160610 to your computer and use it in GitHub Desktop.
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