[swift-evolution] [Proposal] A more liberal placement of defer

Kenny Leung kenny_leung at pobox.com
Mon Jun 6 18:04:20 CDT 2016


This proposal runs counter to the spirit of what defer seems to be meant for in the first place. It’s to save you forgetting to do something (like closing a stream) before you exit a block of code. If you push it down in the code to after the return, then you might as well have just put the code in *before* the return without the defer.

public func doMyThing() {
	let theStream = openStream()
	defer {
		closeStream()
	}
	
	…
	…
	…
	<enough code that it’s off the bottom of the screen>
	return
}

In this case, putting closeStream() after the return would defeat the purpose.

-Kenny


> On Jun 6, 2016, at 12:50 PM, donny wals via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hi,
> 
> When we’re using defer we write some code that we want to execute the moment a scope exits.
> This leads to code that could read like:
> 
> let fibonacci = sequence(state: (0, 1)) { (pair: inout (Int, Int)) -> Int in
>    defer { pair = (pair.1, pair.0 + pair.1) }
>    return pair.0
> }
> 
> What I find strange about this is that we have to write the code that we want to execute after the return before the return.
> 
> I’d like to propose a change to defer that would allow the above code to be written as:
> 
> let fibonacci = sequence(state: (0, 1)) { (pair: inout (Int, Int)) -> Int in
>    return pair.0
>    defer { pair = (pair.1, pair.0 + pair.1) }
> }
> 
> This would make the intent of the code more clear (return first, then mutate state). Not all cases can benefit from this change, but anytime you exit a scope using a return I think it might be more clear to define the defer after the return. The code would more closely mirror the intent of the code.
> 
> A rule of thumb I’ve come up with for this is that whenever you’re using return to exit a scope, any defer in that same scope should be executed regardless of it’s position in that same scope. This proposal would supplement the way defer currently works.
> 
> What do you all think?
> _______________________________________________
> 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