title: convert the reference back to a strong one inside the closure, memory management, swift
body: <p>I'm experimenting the retain cycle in closure like following</p>
  
  <pre><code> class Sample {
          deinit {
              print("Destroying Sample")
          }
  
          func additionOf(a: Int, b:Int) {
              print("Addition is \(a + b)")
          }
  
          func closure() {                
            dispatch_async(dispatch_get_global_queue(0, 0)) { [weak self] in
              self?.additionOf(3, b: 3)   
              usleep(500)                 
              self?.additionOf(3, b: 5)  
            }
          }
      }
  </code></pre>
  
  <p>Later at some point, I'm doing </p>
  
  <pre><code>var sample : Sample? = Sample()
  sample?.closure()
  
  dispatch_async(dispatch_get_global_queue(0, 0)) {
    usleep(100)
    sample = nil
  }
  </code></pre>
  
  <p>The output will be</p>
  
  <pre><code>Addition is 6
  Destroying Sample
  </code></pre>
  
  <p>This is understandable because <code>self</code> is nil out before doing <code>self?.additionOf(3, b:5)</code></p>
  
  <p>If I made a change inside the closure  by creating another variable which references to <code>[weak self]</code> like following</p>
  
  <pre><code>dispatch_async(dispatch_get_global_queue(0, 0)) { [weak self] in
     guard let strongSelf = self else { return }
     strongSelf.additionOf(3, b: 3)
     usleep(500)
     strongSelf.additionOf(3, b: 5)
  }
  </code></pre>
  
  <p>This time, the output is </p>
  
  <pre><code>Addition is 6
  Addition is 8
  Destroying C
  </code></pre>
  
  <p>My question is why <code>strongSelf</code> is not nil out after <code>sample = nil</code>. Is it because it is captured inside the closure before <code>sample = nil</code></p>