Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rule to prefer count(where: { ... }) over filter { ... }.count #295

Merged
merged 2 commits into from
Dec 12, 2024

Conversation

calda
Copy link
Member

@calda calda commented Dec 9, 2024

Summary

This PR proposes a new rule to prefer using count(where: { ... }) over filter { ... }.count.

// WRONG
let planetsWithMoons = planets.filter { !$0.moons.isEmpty }.count

// RIGHT
let planetsWithMoons = planets.count(where: { !$0.moons.isEmpty })

Autocorrect is implemented in nicklockwood/SwiftFormat#1939.

Reasoning

Swift 6.0 (finally!) added a count(where:) method to the standard library.

@calda calda force-pushed the cal--preferCountWhere branch from f60fa7d to 3371c2f Compare December 9, 2024 19:33
@miguel-jimenez-0529
Copy link
Contributor

LGTM

@calda calda force-pushed the cal--preferCountWhere branch from 3371c2f to 2dd922e Compare December 10, 2024 19:45
@calda calda force-pushed the cal--preferCountWhere branch from 2dd922e to 849c8ad Compare December 10, 2024 20:47
@calda calda merged commit 3f6adc3 into master Dec 12, 2024
4 checks passed
@calda calda deleted the cal--preferCountWhere branch December 12, 2024 23:25
Copy link
Contributor

@bachand bachand left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks @calda .

let planetsWithMoons = planets.filter { !$0.moons.isEmpty }.count

// RIGHT
let planetsWithMoons = planets.count(where: { !$0.moons.isEmpty })
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! I imagine that this must be more efficient, especially with large collections.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants