title: How can a closure escape when it's used in a nested function?
body: <p>I'm playing around with a recursively defined data structure. Boiling it down to arrays, this is what I do for <code>map</code>:</p>
  
  <pre><code>func map&lt;T, U&gt;(_ arr: [T], _ mut: T -&gt; U) -&gt; [U] {
      func recMap(_ i : Int) -&gt; [U] {
          if i &gt;= arr.count {
              return []
          } else {
              return [mut(arr[i])] + recMap(i+1)
          }
      }
  
      if arr.count &gt; 0 {
          return recMap(0)
      } else {
          return []
      }
  }
  </code></pre>
  
  <p>This strikes me as a good used of nested functions: the traversal code does not escape the only scope it's needed. (Let's assume that is truly the case here.)</p>
  
  <p>However, Swift complains:</p>
  
  <blockquote>
    <p>Declaration closing over non-escaping parameter 'mut' may allow it to escape.</p>
  </blockquote>
  
  <p>Of course, <code>recMap</code> <em>may</em> do weird things, but it doesn't; is the issue that the compiler can't figure that out?</p>
  
  <p>What deepens my confusion is that this code works:</p>
  
  <pre><code>private func recMap&lt;T, U&gt;(_ arr: [T], _ i : Int, _ mut: (T) -&gt; U) -&gt; [U] {
      if i &gt;= arr.count {
          return []
      } else {
          return [mut(arr[i])] + recMap(arr, i+1, mut)
      }
  }
  
  func map&lt;T, U&gt;(_ arr: [T], _ mut: (T) -&gt; U) -&gt; [U] {
      if arr.count &gt; 0 {
          return recMap(arr, 0, mut)
      } else {
          return []
      }
  }
  </code></pre>
  
  <p>Surely, <code>mut</code> can escape in the same ways now?</p>
  
  <p>What am I missing? Is there a way to make the first version work?</p>