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

Dany St-Amant dsa.mls at icloud.com
Wed Mar 23 22:11:56 CDT 2016

> Le 23 mars 2016 à 05:52, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> a écrit :
>> 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.

Could such new keywords be optional, only required when the compiler see the construct as ambiguous? For simple construct, these new then/do/do/among are in a way useless; and it would be bad to impose them on all to support a rare use case.


More information about the swift-evolution mailing list