title: Deep copying closures in Swift
body: <p>I have a function that cycles between an array of functions, calling them in order with the passed arguments in sequence infinitely. </p>
  
  <pre><code>public extension Array {
      /// Cycles the elements in `self` infinitely.
      /// - warning: Do not call on an empty array.
      public func cycle() -&gt; UnfoldSequence&lt;Element, Int&gt; {
          let count = self.count
          return sequence(state: 0, next: { (index: inout Int) in
              let x = self[index]
              index = (index + 1) % count
              return x
          })
      }
  }
  
  func cycle(funcs: [(((Int, Int)) -&gt; (Int, Int))]) -&gt; (((Int, Int)) -&gt; (Int, Int)) {
      var cycled = funcs.cycle()
      return  { (coords) in
          let current = cycled.next()!
          return current(coords)
      }
  }
  </code></pre>
  
  <p>So if I have these two functions for example:</p>
  
  <pre><code>func leftPattern(tuple:(x: Int, y: Int)) -&gt; (Int, Int) {
      return (tuple.x, tuple.y - 1)
  }
  
  func upPattern(tuple:(x: Int, y: Int)) -&gt; (Int, Int) {
      return (tuple.x - 1, tuple.y)
  }
  </code></pre>
  
  <p>I can cycle between them infinitely:</p>
  
  <pre><code>let leftUp = cycle(funcs: [leftPattern, upPattern])
  </code></pre>
  
  <p>leftUp would be equal to...</p>
  
  <pre><code>[leftPattern, upPattern, leftPattern, upPattern, ...]
  </code></pre>
  
  <p>Trouble is, I need a way to restart this sequence, because as I pass this function around, it starts at the wrong part of the sequence. </p>
  
  <p>Since functions are passed by reference, the solution I thought of would be to somehow deep copy my generated function for example:</p>
  
  <pre><code>let leftUp2 = copy(leftUp)
  leftUp(...) // would use leftPattern for example
  leftUp2(...) // would ALSO use leftPattern, not affected by calling leftUp before
  </code></pre>
  
  <p>Is this possible?</p>