Strange issue with custom "+" operator

This doesn't compile, but why?

struct X {}
struct Y {}
let x = X()

infix operator + : AdditionPrecedence // tried without it
func + (a: X, b: X) -> Y { Y() }
func + (a: Y, b: Y) -> Y { Y() }

let y: Y = x + x // ✅
_ = x + x // ✅
_ = y + y // ✅
_ = (x + x) + (x + x) // ❌ Binary operator '+' cannot be applied to two 'X' operands

Note, that it compiles fine if I change + to something non standard like +++.

5 Likes

Bug. Please file an issue :)

1 Like

The type checker makes certain assumptions about the standard library operators to speed up type checking, so occasionally there are differences in behavior.

However, I checked and this example failed in Swift 6.2 but now works in Swift 6.3. It also fails with the same error if I build with the -enable-constraint-solver-performance-hacks flag in Swift 6.3, so indeed it was caused by one of the older optimizations which has been removed (Roadmap for improving the type checker). I'll add your example to the test suite to be sure it won't break again.

9 Likes