[swift-evolution] Better syntax for deferred?

Developer devteam.codafi at gmail.com
Sat Jan 2 16:49:55 CST 2016


-1. `defer` doesn’t exist just to execute code at the end of blocks, it exists to allow resource cleanup when you have a function with multiple return points or non-trivial scoping.  For example, let’s add an if statement to your code:


func clear() {
   print("1")
   print("3")
   if (theBusiness) {
       print(“4”)
       return
   }
   always { print("2") }
}

Now `always` does not, in fact, model the flow of control through this function and I’m confused about where that finalizer is going to run.  I mean, because it is declared below the if, will it never execute?  Will it always execute as the name implies?  But couldn’t control flow branch before that statement is hit?  It’s a context switch I don’t have to make with `defer` as it currently stands.

> On Jan 2, 2016, at 7:25 AM, Maury Markowitz via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I'm confused about 'defer'. Not the purpose, the chosen syntax. 
> 
> func confusing() {
>    print("1")
>    defer { print("2") }
>    print("3")
> }
> 
> Produces 1,3,2. Trying to describe what is happening here is non-trivial... it runs line 1, then we put line 2 on a stack, then line three runs, then we pop the stack... what?! And stepping through it in the debugger... ugh.
> 
> Unless I missed something obvious, wouldn't placing "code that always has to run at the end" actually *at the end* not make more sense? Like this...
> 
> func clear() {
>    print("1")
>    print("3")
> 
>    always { print("2") }
> }
> 
> Not only is the code clearly expressing its intent, the actual execution is following the source.
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list