[swift-evolution] [Proposal] A more liberal placement of defer
donny wals
donnywals at gmail.com
Mon Jun 6 14:50:04 CDT 2016
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?
More information about the swift-evolution
mailing list