Created
December 8, 2016 15:49
-
-
Save JoshuaSullivan/be8e02b9ad7a03377075791e36160610 to your computer and use it in GitHub Desktop.
A new Sequence type that returns a repeating sequence of values.
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
/// 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