[swift-evolution] [Pitch] Guard/Catch

Benjamin Spratling bspratling at mac.com
Sat Jul 8 17:05:35 CDT 2017

> On Jul 8, 2017, at 4:08 PM, Christopher Kornher <ckornher at me.com> wrote:
> I am opposed to this proposal because it muddies up the language to support what is essentially an edge case. The standard way to exit a function early because an exception is thrown is to make the function itself throw, if it is part of a larger operation. The addition of a few lines of try/catch code is not a great burden and makes the termination of an an exception very clear.

I’ve read your email, but haven’t digested it fully.  One thing I agree with is that most functions which call throwing functions don’t actually use a do…catch block, but instead are merely marked “throws” and the error is propagated back through the stack.  Once I seriously started coding functions with errors, I realized I almost always wanted my errors to reach my view-controller or my business logic so I could present separate UI if a real error occurred, and often my error message depended on the details of the error instance.

> `guard` statements are generally used to set variables that are needed in the body of a function. Using them to save a few lines of exception handing code is a very different use. There is no need to mix two relatively clean syntaxes for a few edge cases and increase cognitive load one more time, 

I disagree with your conclusion on this point.
The “guard” syntax is specifically designed to achieve early return (and placing code associated with early return at the point where it happens) and cleanly installing the returned value into the surrounding scope.  So far it has been used to achieve early return only with optionals, true.  But is that inherent to ‘guard’, or is it merely because that’s the only way it has been used?  The guard does set variables that are needed in the body of the function, and that’s exactly why using guard with values returned from throwing functions makes so much sense, because it does exactly the same thing in a general sense.  The “do”…”catch” structure is intentionally designed differently, to place the “happy path” in one place and place the returns in another place.  I think with guard/else, we’re seeing developers who can handle less cognitive loading find it easier to reason about early return than grouping failures after the happy path.  This proposal hopes to introduce that better language architecture to the catching of errors.

-Ben Spratling

More information about the swift-evolution mailing list