Created
April 17, 2018 04:58
-
-
Save libsteve/838541178dd5066014fc77df4f4e2b53 to your computer and use it in GitHub Desktop.
An iterator to endlessly iterate over the same sequence.
This file contains hidden or 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
struct CycleIterator<Element>: IteratorProtocol, ExpressibleByArrayLiteral { | |
private var elements: [Element] | |
private var offset: Int = 0 | |
init(_ elements: [Element]) { | |
self.elements = elements | |
} | |
init(arrayLiteral elements: Element...) { | |
self.init(elements) | |
} | |
mutating func next() -> Element? { | |
let index = offset % elements.count | |
offset += 1 | |
return elements[index] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment