[swift-evolution] Disallowing unreachable code

Brent Royal-Gordon brent at architechies.com
Wed Mar 29 05:14:25 CDT 2017

> On Mar 28, 2017, at 9:55 PM, Peter Dillinger via swift-evolution <swift-evolution at swift.org> wrote:
>>> Missing 'try' is a fatal issue?
>> That could be argued I suppose, I was referring to unreachable code, unused variables,
>> variables that are never mutated, etc.
> And what about non-exhaustive switch?
> Both of these existing rules seem to violate the principle claimed, because they are hazards to incomplete or experimental changes that might lead people to use quick fixes (try!; default) that are not associated with a warning, whereas a warning instead of the error would (as you claim) signal to the user there are pending fixes before commit.

Here's a different principle: When Swift generates a warning, the mistake has no runtime effect on the behavior of the code, but things like non-exhaustive `switch` or a missing `try` represent code where you haven't told the compiler how to handle some of the circumstances it might encounter.

If you stick a `return` in the middle of some code, the compiler knows exactly how to interpret that: Return there and don't run the code after it. If you write a non-exhaustive `switch`, what is the compiler supposed to do? Fall out of `switch` statement? Trap? It's unclear. Similarly, if there's no `try`—particularly outside of a `do`/`catch` block or `throws` function—what behavior should the compiler assume you want?

Trapping is clearly the proper choice, because Swift's philosophy is to trap whenever the program finds itself in a state that the programmer did not anticipate. And yet you don't want the *lack* of something to cause a trap; you should at least be able to see the operation so you have a chance to recognize the potential to trap. (Implicitly unwrapped optionals are the exception that proves the rule--many programmers ban them because they cause invisible trapping. You don't want people banning `switch` or `throw` statements because of their invisible danger.) Any other option, though, runs the risk of letting a program run off the rails and do the wrong thing.

So we emit an error in these cases because the programmer has written ambiguous code, and the compiler has no good option for resolving the ambiguity. On the other hand, if you use `var` instead of `let`, or write code after a `return`, the instructions your code is giving the compiler are unambiguous; they're just not phrased as well as they could be. So we emit a program that does what your code says and politely point out that you could write it better.

Brent Royal-Gordon

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170329/aabc2c0b/attachment.html>

More information about the swift-evolution mailing list