[swift-evolution] Better syntax for deferred?

Sebastian Mecklenburg mecklenburg at rechenmaschinist.de
Sat Jan 2 10:48:54 CST 2016


I don’t think it’s confusing, I read ‘defer’ a ‘do it later’ and that’s just what it does. And the deferred calls are not always necessary so they can’t always be placed at the end.

The only thing to be aware of is that the order is reversed (or not determined), so

func testDefer() {
    defer {print("deferred call1")}
    defer {print("deferred call2")}
}

prints

deferred call2
deferred call1

But I think that is the logical consequence of the way how defer is supposed to work, so that’s OK too. One just has to be aware of it.

> On 02 Jan 2016, at 15:25, 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