nicklockwood / SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
MIT License
7.87k stars 638 forks source link

redundanttype rule is not smart enough #1637

Open elenzil opened 7 months ago

elenzil commented 7 months ago

Hello!

with swiftformat version 0.52.8, using a command line like this: swiftformat --redundanttype inferred --swiftversion 5.9 .

the following code:

let a: Int = (5 + 3)
let b: Int = 6

is reformatted to this:

let a: Int = (5 + 3)
let b = 6

I would like it to be reformatted to this:

let a = (5 + 3)
let b = 6

Similar behavior if assigning to the value of a function, etc.

In actual code I work with, this catches a fairly small percentage of redundant type declarations.

Note, it will strip the type from the a declaration if the parens are removed:

let a: Int = 5 + 3

becomes

let a = 5 + 3
nicklockwood commented 6 months ago

@elenzil IIRC this was a deliberate choice. Expressions in Swift (especially chains of operators like +) can exponentially increase compile times, and the common workaround is to add an explicit type (which you wouldn't then want SwiftFormat to remove).

I don't actually recall why the separate redundantParens rule isn't applied in this case, which would then also cause the explicit type to be removed. That might be a bug or it may have been a deliberate choice for similar reasons (I should probably document these decisions better).