swift icon indicating copy to clipboard operation
swift copied to clipboard

Unexpected behavior with weak listener in closure with switch-expression

Open benpious opened this issue 2 years ago • 1 comments

Description In Swift 5.8, this closure would have been inferred to have a return type of Void. In 5.9, it is inferred to have a type of Void?, which breaks in functions that expect a return of void, such as Rx's subscribeNext. This appears to be due to the new behavior of treating switch as an expression in this context.

This is a common pattern in pre-structured concurrency, UIKit code, it might be worth addressing despite the fact that the fix is trivial. It is also a breaking change, not sure if that was intended (I haven't re-read the SE for this yet, apologies if this is already addressed there).

Steps to reproduce

class Listener {
     func f() { }
}
var listener = Listener()
let closure = { [weak listener] someInt in 
    switch int {
          case 0: 
             listener?.f()
          default:
            listener?.f()
    }
}
func subscribe(closure: (Int) -> ()) {

}
subscribe(closure: closure)

Expected behavior This code compiles. Environment

  • Swift compiler version info: 5.9
  • Xcode version info: current Xcode 15 beta

benpious avatar Jun 06 '23 18:06 benpious

CC: @airspeedswift @xedin

tbkka avatar Jun 06 '23 18:06 tbkka