[Swift-devel] the switch statement

Mihael Hategan hategan at mcs.anl.gov
Fri May 29 18:46:02 CDT 2015


So I have some bad news. The switch statement is broken.

In most c-like languages, the case expressions are restricted to
literals. The reason is that it is the only way to reliably check for
conflicting cases. Allowing arbitrary expressions means that you can't
assert that the cases are non-overlapping at compile-time.

Swift allows expressions in cases. Furthermore, it implements the cases
as 

if (expr == case1expr) {statements1}
else if (expr == case2expr) {statements2}
...

This means that when two cases have the same value, the second one will
be quietly ignored.

We have two options I think:

1. Remove the else. Run statements in all cases that have the right
value
2. Restrict case expressions to literals and check that there are no two
cases with the same value at compile-time.

Thoughts?

Mihael




More information about the Swift-devel mailing list