title: Swift completion in defer
body: <p>I like defer, because in complex functions with multi-case scenario, I can't forget calling completion before the function ends.</p>
  
  <p>But when the completion is passed to another function, it shouldn't be run in first function's defer.</p>
  
  <p>This is what I usually do:</p>
  
  <pre class="lang-swift prettyprint-override"><code>func doSomething(completion: ()-&gt;()) {
      /// Set this to false, before passing the completion to another function.
      var runCompletionInDefer = true
      defer {
          if runCompletionInDefer { completion() }
      }
      runCompletionInDefer = false
      doSomethingElse { completion() }
  }
  
  func doSomethingElse(completion: ()-&gt;()) {
      completion()
  }
  </code></pre>
  
  <p>Is there a better solution?</p>
  
  <p>With this approach, before passing the completion to another function, you still must remember to do:</p>
  
  <pre class="lang-swift prettyprint-override"><code>runCompletionInDefer = false
  </code></pre>