[swift-evolution] An implicit return for guard
Yarden Eitan
yarneo at gmail.com
Mon Jun 20 01:30:25 CDT 2016
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160620/2be8f5ba/attachment.html>
More information about the swift-evolution
mailing list