SwiftLint icon indicating copy to clipboard operation
SwiftLint copied to clipboard

Add configuration for `for_where` rule

Open marcelofabri opened this issue 2 years ago • 1 comments

New Issue Checklist


While updating our code base to use SwiftLint 0.48.0, I realized for_where is now triggering for some cases where it wasn't before. It's great to fix false positives, but it made me realize that this rule might not be always wanted.

In several places of our app, we use an if inside a for to test if any object in a given array meets a condition. Some examples:

for clause in clauses {
    if clause.evaluate(object) {
        return true
    }
}
return false
for featureSet in minimalSupportedFeatureSets {
    if device.supportsFeatureSet(featureSet) {
        return true
    }
}

return false

While we could update them to use where, I kind of feel like it's against the spirit of the rule and it makes code harder to read:

for clause in clauses where clause.evaluate(object) {
    return true
}
return false

Instead, the rule could have a configuration like allow_single_return to not trigger a violation if the only statement inside the if is a return statement.

marcelofabri avatar Jul 26 '22 08:07 marcelofabri

I also suggest to define an exception when the for clause and/or the if condition are pretty long and rewriting the code using where would trigger a line length warning.

futuretap avatar Sep 16 '22 09:09 futuretap

@marcelofabri The example you give can be rephrased as below:

return clauses.contains { clause in clause.evaluate(object) }

I am curious that is there another scenario you need allow_for_as_filter?

PangYenChen avatar Nov 26 '23 11:11 PangYenChen