SwiftFormat icon indicating copy to clipboard operation
SwiftFormat copied to clipboard

Add option to not remove implicit `self` in closures

Open honghaoz opened this issue 2 years ago • 4 comments

The self is unexpectedly removed in the following example code:

extension Optional {

  func doSomething() -> Wrapped? {
    self
  }
}

class SomeViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    let closure = { [weak self] in
      self.doSomething()?.view.layoutIfNeeded() // <-- this `self` is removed, but it's required!
    }

    let closure2 = { [weak self] in
      self?.view.layoutIfNeeded() // <-- this `self` is kept, which is correct
    }
  }
}

Used SwiftFormat 0.51.7 with Swift 5.8.

honghaoz avatar May 01 '23 22:05 honghaoz

Could we provide an option for redundantSelf such as init-and-closure-only? I'm not a fan of the Swift 5.8's implicit self in closures.

honghaoz avatar May 01 '23 22:05 honghaoz

Looks like https://github.com/nicklockwood/SwiftFormat/commit/151bcf96e748e56ff991aa65b541927c20104f07 already fixed this issue. But still it would be great to have an option to keep self in closures.

honghaoz avatar May 01 '23 22:05 honghaoz

How is the progress of this issue? I found that using 5.9 still automatically removes self from the closure, which is not what I want.

swiftformat . --swiftversion 5.9

tisfeng avatar Dec 17 '23 16:12 tisfeng

This issue is causing build errors for me after running SwiftFormat: Reference to property 'someProperty' in closure requires explicit use of 'self' to make capture semantics explicit.

DePasqualeOrg avatar May 08 '24 21:05 DePasqualeOrg