title: Different Behaviour of defer statement
body: <p>I have code on logout button, where I'm using <code>defer</code> statement. </p>
  
  <p>I'm wondering when changing position of <code>defer</code> statement code inside action method scope.</p>
  
  <ol>
  <li>I have added <code>defer</code> statement at the end of method, it's show me warning.</li>
  </ol>
  
  <blockquote>
    <p>'defer' statement before end of scope always executes immediately;
    replace with 'do' statement to silence this warning</p>
  </blockquote>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>override func sendButtonTapped(sender: Any) {
  
      self.deleteCoreData()
      self.clearUserDefaults()
  
      // Clear view context
      AppDelegate.shared.persistentContainer.viewContext.reset()
  
      ....
      ....
  
      // Call after all code execution completed in this block's Scope
      defer {
          // Set isUserLoggedIn and change root view controller.
          UserDefaults.Account.set(false, forKey: .isUserLoggedIn)
          AppDelegate.shared.setRootViewController()
      }
  }
  </code></pre>
  
  <ol start="2">
  <li>Then, I have added <code>defer</code> statement at start of method, it's show nothing.</li>
  </ol>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>override func sendButtonTapped(sender: Any) {
  
      // Call after all code execution completed in this block's Scope
      defer {
          // Set isUserLoggedIn and change root view controller.
          UserDefaults.Account.set(false, forKey: .isUserLoggedIn)
          AppDelegate.shared.setRootViewController()
      }
  
      self.deleteCoreData()
      self.clearUserDefaults()
  
      // Clear view context
      AppDelegate.shared.persistentContainer.viewContext.reset()
  
      ....
      ....
  }
  </code></pre>
  
  <p>Can anyone explain what exactly happening with <code>defer</code> statement?</p>