[swift-evolution] [proposal] Allow trailing closures in 'guard' conditions

Brent Royal-Gordon brent at architechies.com
Wed Mar 23 04:52:08 CDT 2016

> The solution is simple: allow trailing closures in guard bodies.  This would allow this silly example to compile correctly:
> func f(arr : [Int]?) {
>   guard let x = arr?.map {$0+1} else {
>     preconditionFailure()
>   }
>   // ...
> }

This sounds perfectly reasonable.

> Alternatives considered
> There are three primary alternatives: do nothing, expand the scope of ‘if' and ‘while’ conditions as well, and significantly change the syntax of guard.

A fourth alternative would be to change the syntaxes of `if` and `while` (and probably `for` and `switch`) to also have a keyword in this position.

	if expr then { code }
	while expr do { code }
	for elem in expr do { code }
	switch expr among { code }

I'm not going to say I advocate for this option, but it *would* clearly mark the end of the condition so that trailing closures could be brought to all of these statements, so it seemed worth mentioning.

Brent Royal-Gordon

More information about the swift-evolution mailing list