Nested If

ID

swift.nested_if

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Complexity

Language

Swift

Tags

complexity

Description

Reports an if statement whose nesting depth exceeds a configurable threshold. The depth counts enclosing if, guard, switch, for-in, while and repeat-while statements within the same function body.

Configuration

  • maxDepth (default 4) — depth strictly greater than this value is flagged.

Rationale

Each level of nesting hides the precondition under which the inner code runs. Past four levels, readers must hold too many active conditions in their head and shape coverage by hand. The test count grows multiplicatively with the depth and the meaning of each branch becomes harder to reason about.

Notes

  • else if chains are siblings of the outer if, not children of it — the rule does not penalise them.

  • Only the inner-most offending if is flagged so the issue count tracks the number of refactorable spots, not the size of the chain.

Remediation

Common refactors are:

  • invert the leading condition and guard early;

  • extract the deepest branch into a helper function;

  • replace a deeply-nested chain of if with a switch over a single value.

// Hard to read — many active conditions.
if let user = user {
    if user.isActive {
        if let email = user.email {
            if isValid(email) {
                send(email)
            }
        }
    }
}

// Same logic, flat.
guard let user = user, user.isActive else { return }
guard let email = user.email, isValid(email) else { return }
send(email)