title: Cycle iterator in Swift
body: <p>In Python, there is <a href="https://docs.python.org/3.5/library/itertools.html#itertools.cycle" rel="nofollow"><code>itertools.cycle</code></a>, which takes an <code>iterable</code> and makes an iterable iterator that repeatedly yields the contents from the source.</p>
  
  <p>I would like to replicate this behavior in Swift.</p>
  
  <p>A candidate for replicating this behavior would be the standard library's <code>repeatElement(_:count:)</code>: doing <code>repeatElement(seq, count: 5).flatMap({$0})</code> creates an array of the elements of <code>seq</code> five times, but this does not meet my requirements as it only repeats <code>seq</code> a finite number of times. Additionally, it creates an <code>Array</code> of length <code>5 * seq.length</code>, where only a cache of the length of <code>seq</code> is actually needed.</p>
  
  <p>So the question is: how can I create an infinite <code>Sequence</code> by repeating the elements of a source <code>Sequence</code>? The solution should not have a space cost more than <code>O(n)</code>. (A <code>O(1)</code> would be impossible to guarantee in Swift, as a <code>Sequence</code> <a href="https://developer.apple.com/reference/swift/sequence#2239542" rel="nofollow">makes no guarentee that it can be iterated multiple times</a>.)</p>