swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.51k stars 10.35k forks source link

[SR-7047] Empty case block might be intended for multiple "or" patterns. #49595

Open 41412bb9-c79a-4f5a-8a7f-383cb40aa74b opened 6 years ago

41412bb9-c79a-4f5a-8a7f-383cb40aa74b commented 6 years ago
Previous ID SR-7047
Radar None
Original Reporter @rintaro
Type Improvement
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 0 | |Component/s | Compiler | |Labels | Improvement | |Assignee | None | |Priority | Medium | md5: c81fffcf7a2007158fa3f9510255f010

Issue Description:

switch val {
case 0:
case 1:
  return foo()
default:
  return bar()
}

Multiple empty case labels in switch are a common idiom in C family languages.
In current Swift, this is diagnosed as:

error: 'case' label in a 'switch' should have at least one executable statement
case 0:
^~~~~~~
        break

However, the intention here is probably 0 or 1:

switch val {
case 0, 1:
  return foo()
default:
  return bar()
}

We should offer a fix-it to this as well.

CodaFi commented 6 years ago

An easier and more general fixit would be to offer to insert a fallthrough. In case the user binds arguments in a tuple pattern, merging cases like this would need to do a rename on those arguments and any uses of them in the case body under the final pattern. Come to think of it, this would make a great refactoring action.