Rule Request: Prefer specialized collection types over Array literals
Nobody has claimed this yet.
- Dominant language
- Swift
- Stars
- 19.7k
- Forks
- 2.3k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 11
Description
New Issue Checklist
- Updated SwiftLint to the latest version
- I searched for existing GitHub issues
New Rule Request
Please describe the rule idea, format this issue's title as Rule Request: [Rule Name] and describe:
The idea here is for a rule, called "Prefer specialized collection types over Array literals", which would trigger in the following two cases:
- when calling a function that takes a generic
Collectionparameter, but passing in anArrayliteral containing only a single element. - when calling a function that takes a generic
SequenceorCollectionparameter, but passing in an emptyArrayliteral.
Why should this rule be added?
- it's primarily a performance rule, since using these specialized collection types allows avoiding having to allocate and initialize an Array instead.
Examples that would / would not trigger the rule:
func f1(_ elements: some Collection<String>) { ... }
func f2<S: Sequence>(_ elements: S) { ... }
func f3(_ elements: [String]) { ... }
f1([""]) // would trigger, suggesting that `CollectionOfOne("")` be used instead
f2([""]) // would trigger, suggesting that `CollectionOfOne("")` be used instead
f3([""]) // would not trigger
f1(["", ""]) // would not trigger
f2(["", ""]) // would not trigger
f3(["", ""]) // would not trigger
f1([]) // would trigger, suggesting that `EmptyCollection()` be used instead
f2([]) // would trigger, suggesting that `EmptyCollection()` be used instead
f3([]) // would not trigger
Should the rule be configurable?
- i guess it'd make sense to allow selecting that you want only one of the
EmptyCollectionorCollectionOfOnesuggestions to happen.
Should the rule be opt-in or out-out?
- it should probably be opt-in, i.e. disabled by default.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No implementation files or tests are named. Start with the issue's Swift examples and inspect SwiftLint's existing rule patterns and tests to determine how collection literals and parameter types can be analyzed. Done means an opt-in rule handles the single-element and empty cases, excludes Array parameters, and supports the proposed suggestion configuration.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100