This is a rule request. I'm willing to implement this myself and send a PR, but before doing that I'd like to know if the rule is wanted or not. To explain the desired rule, I'd like to first post the custom rule we are already using in our projects:
if_as_guard:
included: ".*.swift"
regex: '\n *if [^\{]+\{\s*return[^\n]*\n *\}(?! *else)'
name: "If as Guard"
message: "Don't use an if statement to just return – use guard for such cases instead."
severity: warning
I felt like this rule might be useful for other projects as well, which is why I'm posting it. What do you think about it? For us it helps a lot to prevent common issues and enforce a shared style.
Rationale
Early returns are considered bad practice amongst several languages due to the fact that they make following the code logic harder. Sometimes they're useful though to keep the code clean. In Swift we have the guard statement which already indicates to people, that there is some kind of early return at the beginning of a line (unlike the if statement where any code without a return could be in the body). Therefore when an if statement is used just to return something, then in all cases a guard would be better used instead. This is actually what guard was designed for, so it should be used.
Note that this rule does not cover more complicated cases with multi-line if statement bodies to ensure it is always better to have a guard statement instead (otherwise there might be edge cases).
A few examples:
// ❌ not acceptable
if x > 5 {
return false
}
// ✅ acceptable
guard x <= 5 else {
return false
}
This is a rule request. I'm willing to implement this myself and send a PR, but before doing that I'd like to know if the rule is wanted or not. To explain the desired rule, I'd like to first post the custom rule we are already using in our projects:
I felt like this rule might be useful for other projects as well, which is why I'm posting it. What do you think about it? For us it helps a lot to prevent common issues and enforce a shared style.
Rationale
Early returns are considered bad practice amongst several languages due to the fact that they make following the code logic harder. Sometimes they're useful though to keep the code clean. In Swift we have the
guardstatement which already indicates to people, that there is some kind of early return at the beginning of a line (unlike theifstatement where any code without a return could be in the body). Therefore when an if statement is used just to return something, then in all cases a guard would be better used instead. This is actually what guard was designed for, so it should be used.Note that this rule does not cover more complicated cases with multi-line if statement bodies to ensure it is always better to have a guard statement instead (otherwise there might be edge cases).
A few examples: