[swift-evolution] An implicit return for guard

Xiaodi Wu xiaodi.wu at gmail.com
Mon Jun 20 01:37:34 CDT 2016


This has been suggested several times before. See the conversations below:

http://article.gmane.org/gmane.comp.lang.swift.evolution/11563/

http://article.gmane.org/gmane.comp.lang.swift.evolution/6770/



On Mon, Jun 20, 2016 at 01:30 Yarden Eitan via swift-evolution <
swift-evolution at swift.org> wrote:

> Dear community,
>
> While using ‘guard’ with much appreciation, I noticed a few cases where I
> would of hoped for better and more concise code.
>
> As of now, you receive a compiler error if your guard statement does not
> provide an ending statement such as return/break/etc. at the end.
> It is informative, but in many cases such a statement makes the code
> repetitive and less concise.
>
> As an example of cases where there are multiple guards done sequentially
> to avoid very nested and unclear ‘if's:
>
> guard let resp = response as? HTTPURLResponse else {
>     failure(…)
>     return
> }
>
> guard let  resp.statusCode == 200 else {
>     failure(…)
>     return
> }
>
> guard let respData = data else {
>     failure(…)
>     return
> }
>
> guard let res = parse(respData) else {
>     failure(…)
>     return
> }
>
> success(…)
>
> As you can see in this example, while the different failures can (and
> should) provide different information for completion, we always have to add
> a repetitive return after them.
>
> My proposal is to allow for an implicit return when no ending statement is
> provided. We could take this one step further and have the compiler aware
> of it’s most inner scope and see if it is a while loop for example and
> implicitly allow a break. But I think at least as a first step, by having
> an implicit “return” we are saving the repetitiveness on many cases where
> there are multiple guard statements and the return from them is obvious.
>
> This goes along the line of the Swift “switch” statement, which doesn’t
> follow it’s predecessors and force a “break” but rather it is already
> implicitly there.
>
> If this proposal is too much of a leap, an alternative is to allow an
> implicit return but provide a warning (not an error). This warning can be
> suppressed using an @implicitreturn prefix to the guard statement or
> something along those lines (@implicitreturn guard a = b else {
> print(“foo”) } ).
>
> Glad to hear your thoughts on the matter.
>
> Best,
> Yarden
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160620/771c4631/attachment.html>


More information about the swift-evolution mailing list