The vast majority of the guard
statements I write contain a single statement in its else
block:
return
return value
throw ErrorType()
continue
break loopLabel
- etc…
This is fine and good, and I would never suggest we rename or shorten these phrases as their intent is particularly clear, but years later, I still end up not typing the curly braces on first pass, only remembering to add them after the fact. Since I don't think this particular iteration of a guard shorthand has been pitched yet, how do people feel about optionally dropping the curly braces when only a single statement lives in the else block?
Some before and afters:
Simple Unwrapping, Return nil
guard let unwrappedValue else { return nil }
guard let unwrappedValue else return nil
Multiple Checks and Throw Error
guard currentLoad > watermark, let excessLoadManager else {
throw LoadError.missingExcessManager
}
guard currentLoad > watermark, let excessLoadManager
else throw LoadError.missingExcessManager
Loops
for job in sortedJobs {
guard job.isValid else { break }
job.start()
}
for job in sortedJobs {
guard job.isValid else break
job.start()
}
Multi-statement else blocks would continue to require curly brackets as is the case today:
var firstInvalidJob: Job?
for job in sortedJobs {
guard job.isValid else {
firstInvalidJob = job
break
}
job.start()
}
Although I understand why we don't allow single statements without braces for if-statements, loops, and functions, and would never argue to remove braces there, I think the unique spelling of guard ... else
statements actually makes things more readable when the else
phrase can flow directly into the single statement without interruption, much in the same way dropping parentheses from if
conditionals helps readability there.
I don't believe introducing this new sugar would break any existing code by introducing ambiguity, nor would using it cause any parsing issues, but I could very much be wrong here. All this said, this is my first time submitting a pitch to the language, so I would appreciate any help I could get if there is any shared interest in making this happen.