realm / SwiftLint

A tool to enforce Swift style and conventions.
https://realm.github.io/SwiftLint
MIT License
18.45k stars 2.2k forks source link

[0.55.1] False positive on `unused_element` where element and index are used separately in subsequent blocks #5600

Open michaeleustace opened 1 month ago

michaeleustace commented 1 month ago

New Issue Checklist

Describe the bug

The rule should not trigger when the enumerated index and element are used in separate subsequent blocks

Environment

# insert yaml contents here
protocol Rule {
  func isValid() -> Bool
}

let rules: [Rule] = [rule1, rule2]
let messages = ["msg1", "msg2"]

// This triggers a violation:
rules.enumerated()
    .first { $0.element.isValid() == false }
    .flatMap { messages[$0.offset] }
mildm8nnered commented 1 month ago

So unfortunately we do only cover the first block - I couldn't find a good way to keep track of the variables through subsequent blocks - see #5498 for discussion. There were no examples of subsequent block usage in the open source projects that SwiftLint gets tested against, so we hoped that this would not affect many people.

If that particular idiom is common in your codebase, you could disable the rule locally, or in your configuration.

SimplyDanny commented 3 weeks ago

While the advice the rule is providing might be misleading in this case, it still highlights an issue in the code. Because it could indeed be rewritten entirely without the .enumerated() as:

rules.firstIndex { !$0.isValid() }.flatMap { messages[$0] }