For Where

ID

swift.for_where

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Swift

Tags

code-smell, idiomatic

Description

Reports a for x in xs { …​ } loop whose body is a single if cond { …​ } without an else branch. The same shape can be written for x in xs where cond { …​ }, which expresses the filter directly.

for x in xs {
    if x.isReady { process(x) }              // FLAW
}

for x in xs where x.isReady {                // OK
    process(x)
}

for x in xs {
    if x.isReady { go(x) } else { skip(x) }  // OK — has else
}

Rationale

The where clause was added specifically so the predicate sits next to the iteration — readers see the filter without scanning the body, and the loop’s indentation reflects the actual work rather than a nested conditional. The compiled code is the same.

Remediation

Move the predicate to the loop header:

for x in xs where x.isReady {
    process(x)
}

The rule does not fire when the loop already has a where clause, when the inner if has an else branch, or when the body contains more than one statement — those cases would need a real refactor.