Chelsea Shawra
Chelsea Shawra

Reputation: 1733

Unused Optional Binding Violation: Prefer `!= nil` over `let _ =` (unused_optional_binding) while using swiftlint

I have defined a class for slide menu controller. So I have got the following code like this:

 open override func closeLeft() {
    guard let _ = leftViewController else { // If leftViewController is nil, then return
      return
    }
    self.delegate?.leftWillClose?()
    leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true)
    closeLeftWithVelocity(0.0)
    setCloseWindowLevel()
  }

But I have got the following warning while linting with swift lint. The warning shown is like below: Warning

How to resolve this warning?

Upvotes: 3

Views: 5286

Answers (2)

David Pasztor
David Pasztor

Reputation: 54706

The whole point of optional binding is to get a safely unwrapped copy of the original optional object that you can use safely, even if your original object could be modified by other threads as well. So don't discard the safely unwrapped value, use that value later on instead of doing optional chaining on the optional value.

open override func closeLeft(){
    guard let leftVC = leftViewController else { return }

    self.delegate?.leftWillClose?()
    leftVC.beginAppearanceTransition(isLeftHidden(), animated: true)
    closeLeftWithVelocity(0.0)
    setCloseWindowLevel()
}

Upvotes: 3

Martin R
Martin R

Reputation: 539685

Don't discard the value of the optional binding, use it!

Instead of testing for nil and then optional chaining later

open override func closeLeft() {
    guard let _ = leftViewController else { return } 
    // ...
    leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true)
    // ...
}

assign the unwrapped value to a local variable and use it:

open override func closeLeft() {
    guard let leftVC = leftViewController else { return } 
    // ...
    leftVC.beginAppearanceTransition(isLeftHidden(), animated: true)
    // ...
}

This is simpler because leftViewController is unwrapped only once, not twice.

Upvotes: 1

Related Questions