Swift

Swift

Made by DeepSource

Avoid using unneeded break statements SW-R1018

Anti-pattern
Minor

Unneeded break statements are often found in switch cases in Swift. These break statements are redundant since they are executed automatically at the end of each case block. There is no harm in using break explicitly, but it can make the code less readable and may confuse other developers working on the same codebase.

Using unneeded break statements can also introduce bugs in the code. If a developer adds new code after the break statement, thinking that it will not be executed, they may be surprised to find that it is executed. This can lead to unexpected behavior and bugs.

To fix this issue, simply remove any unneeded break statements in switch cases. Here are examples of both the wrong way and the recommended way to write switch cases:

Bad practice

switch day {
case 1:
    print("Monday")
    break
case 2:
    print("Tuesday")
    break
default:
    print("Other day")
    break
}

Recommendation

switch day {
case 1:
    print("Monday")
case 2:
    print("Tuesday")
default:
    print("Other day")
}

References