realm / SwiftLint

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

Rule Request: Favor Key Path Expressions as Functions When Using Map & Filter #3082

Open 72A12F4E opened 4 years ago

72A12F4E commented 4 years ago

As of Swift 5.2 you can now use a key path expression as a function when calling map/filter/etc.

I am proposing a rule that would identify & flag classic function calls that could be expressed using the new key path style.

Good

users.map(\.email)
users.filter(\.isAdmin)

Bad

users.map { $0.email }
users.filter { $0.isAdmin }
users.filter { user in
    return user.isAdmin 
}

I am not sure if this should be opt-in or not, but I would suggest that this be enabled by default.

ZevEisenberg commented 3 years ago

FYI, key paths can be quite slow currently, because they're not optimized. That might be good to add as a caveat in this rule's description. I just changed a bunch of { $0.foo } to (\.foo) in my app, only to revert the change when it choked while running tests. More info: https://bugs.swift.org/browse/SR-9323