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

Erica Sadun erica at ericasadun.com
Wed Mar 23 07:11:22 CDT 2016


I don't think this issue arises if you use the rule that functional closure arguments (returning values) shouldn't trail:

func f(arr : [Int]?) {
    guard let x = arr?.map({ $0+1 }) else { // compiles
        preconditionFailure()
    }
}

That said, this seems like a positive tweak and I have no problem with its adoption.

-- E

> On Mar 23, 2016, at 3:52 AM, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> 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
> Architechies
> 
> _______________________________________________
> 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