nicklockwood / SwiftFormat

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

Single assign expression closures with optional chaining on lhs and `redundantVoidReturnType` #1578

Open zienag opened 11 months ago

zienag commented 11 months ago

Hi! Just updated to new version of swiftformat, and faced a small problem. Given some closure, that consists of single assigning expression that has optional chaining on left hand side, compiler inferes that closure of type () -> Void?. To fix it, explicit Void is needed, but swiftformat deletes it.

let handler = { [weak self] () -> Void in
  self?.x = 1
}
> -- rules applied: redundantVoidReturnType
// type of handler is now () -> Void?    
let handler = { [weak self] () in
  self?.x = 1
}

Maybe swift format can check for optional chaining on lhs of assign in that case?

% swiftformat --version
0.52.8
nicklockwood commented 10 months ago

This is a know issue. Per the README:

The redundantVoidReturnType rule can inadvertently alter the type signature for closures, for example in cases where the closure calls a @discardableResult function. To solve this you can either fix it on a per-case basis by adding a // swiftformat:disable:next redundantVoidReturnType comment directive to disable the rule for a specific call site, or you can add --closurevoid preserve to your configuration to disable the rule completely for closures (regular functions or methods aren't affected).