realm / realm/SwiftLint

Rule Request: If as Guard

Open
#1,634 5 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

rule-request
Dominant language
Swift
Stars
19.7k
Forks
2.3k
Avg merge
1d 1h
Merged PRs (30d)
11

Description

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
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the custom YAML rule and Swift examples in the issue, then inspect SwiftLint's existing rule implementations and tests for comparable syntax checks. Confirm that the proposed rule is wanted and define its behavior for single-line return-only if bodies. Done means the rule is implemented with coverage for the shown acceptable and unacceptable cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
swift
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.