swift icon indicating copy to clipboard operation
swift copied to clipboard

Add rule to infer property types from the right-hand-side value rather than writing the type explicitly on the left-hand side

Open calda opened this issue 3 months ago • 1 comments

Please react with 👍/👎 below if you agree or disagree with this proposal.

Summary

This PR proposes a new rule to prefer letting the type of a property be inferred from the right-hand-side value rather than writing the type explicitly on the left-hand side:

// WRONG
let sun: Star = .init(mass: 1.989e30)
let earth: Planet = .earth

// RIGHT
let sun = Star(mass: 1.989e30)
let earth = Planet.earth

Autocorrect support for this rule is implemented in https://github.com/nicklockwood/SwiftFormat/pull/1640.

Reasoning

We already have a rule to omit redundant types. It converts let sun: Star = Star() to let sun = Star(), rather than to let sun: Star = .init().

The syntax with inferred types is more idiomatic, and is much more common, than the syntax with explicit types.

I briefly checked the frequency of these two styles in our codebase with a regex search:

  • Syntax with implicit types (let sun = Star() or let earth = Planet.earth, etc):
    • ~20,000 matches using the regex ((let)|(var)) \w+ = [A-Z]+\w+(\.|\()
  • Syntax with explicit types (let sun: Star = .init(), etc)
    • ~5,000 matches using the regex ((let)|(var)) \w+: \w+ = \..

This rule only applies to simple cases where the right-hand side starts with a leading dot (meaning we know that the RHS value refers to a static member of the type written on the LHS). For other cases, we don't state a preference.

calda avatar Mar 13 '24 23:03 calda