[swift-evolution] Better syntax for deferred?

Nicky Gerritsen nickygerritsen at me.com
Sat Jan 2 08:38:33 CST 2016


Defer is used to make code *always* run, even if the function terminates early. Imagine:

func doSomethingWith(x: Int) {
	print(“1”)
	defer { print(“2") }
	if x > 3 { defer { print(“yay”); return }
	print(“3”)
}

Now print(“2”) will always happen, even if the if is true. Placing it at the end this will not be the case. The “yay” will only be printed in the case of the if.
In general we can not place the defer at the end, because it only should run if the code “comes by” the call.

Regards,

Nicky

> On 2 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

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 842 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160102/b49a3f8d/attachment.sig>


More information about the swift-evolution mailing list