[swift-evolution] Code blocks and trailing closures

Rien Rien at Balancingrock.nl
Mon Mar 20 10:06:25 CDT 2017


> On 20 Mar 2017, at 15:42, Haravikk <swift-evolution at haravikk.me> wrote:
> 
> 
>> On 20 Mar 2017, at 14:24, Rien via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> Another solution to the original problem would be to allow the parameter name of the closure outside the functions parenthesis:
>> 
>> func test(a: Int, onError: ()->Void) {…}
>> 
>> could be called like this:
>> 
>> test(5) onError: { myErrorHandler() }
> 
> When you get onto that kind of syntax the obvious question is, what's wrong with:
> 
> 	test(5, onError: { myErrorHandler() })
> 
> To me there's no real difference, in fact all that's changed now is that a round bracket is at the end; while being within the parenthesis is a little noisier, it's also clearer what's going on. Consider, if the body of the closure were very long:
> 
> 	test(5, onError: {
> 		// Lots
> 		// and
> 		// lots
> 		// of
> 		// code
> 	})
> 
> Here the closing round bracket reminds me that this is the end of a closure being passed to a function, rather than some other code block and, if properly indented, it should be easy to jump to whatever that function is.
> 
> It could just be my personal preference; I'm generally uncomfortable with the use of trailing closures except for language-like constructs such as .forEach, and I've never had any problem using closures within the function's parenthesis, but it just seems like there's a point at which we're bolting so much onto trailing closures, that you really do have to ask what's so wrong with just passing the closure normally?

The only (slight) advantage is that using trailing closures you can be sure that you have seen all parameters that are necessary inside the function.

Compare:

test(5, onError: {
   // Lots
   // and
   // lots
   // of
   // code
}, 1)

test(5, 1) onError: {
   // Lots
   // and
   // lots
   // of
   // code
}

But I agree, the difference is probably not worth it.

I will start using the inline notation, and see how that works out.

Rien.


More information about the swift-evolution mailing list