# Defer with local variable's state

**URL:** <https://forums.swift.org/t/defer-with-local-variables-state/3755>\
**Category:** Using Swift\
**Created:** [August 11, 2016, 2:16pm UTC](https://forums.swift.org/t/defer-with-local-variables-state/3755 "2016-08-11T14:16:14Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [August 11, 2016, 3:39pm UTC](https://forums.swift.org/t/defer-with-local-variables-state/3755/2 "2016-08-11T15:39:58Z")

</div>

This is a bug. Defer should track updates of the variable. Would you mind filing this at bugs.swift.org? Do you happen to know whether it reproduces only in debug or release builds, or both?

-Joe

> **···**
>
> > On Aug 11, 2016, at 7:16 AM, Sebastian Hagedorn via swift-users \<swift-users@swift.org\> wrote:
> > 
> > We often write code that returns early, but has to make sure a bit of code (e.g., a completion handler) is always called whenever we return, which seems like a great use case for defer. I started to write this:
> > 
> > func execute(with completion: ((Bool) -\> Void)?) {  
> > &nbsp;&nbsp;var success = false  
> > &nbsp;&nbsp;defer {  
> > &nbsp;&nbsp;&nbsp;&nbsp;// should always execute with the current state of success at that time  
> > &nbsp;&nbsp;&nbsp;&nbsp;completion?(success)  
> > &nbsp;&nbsp;}
> > 
> > &nbsp;&nbsp;guard … else {  
> > &nbsp;&nbsp;&nbsp;&nbsp;// completion is expected to be executed with false  
> > &nbsp;&nbsp;&nbsp;&nbsp;return  
> > &nbsp;&nbsp;}
> > 
> > &nbsp;&nbsp;success = true
> > 
> > &nbsp;&nbsp;// completion is expected to be executed with true  
> > }
> > 
> > However, it seems that defer copies the state of success, which means any update to the variable is not respected, and the completion block is always called with false.
> > 
> > Is there a way to make this work? I could image to call a function within the defer block that evaluates the success (e.g., depending on the state of an instance variable), but using a local variable seems to encapsulate this a lot better.

---

_[View the full topic](https://forums.swift.org/t/defer-with-local-variables-state/3755)._
