Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode 10.1 swift 4.2 operator overloading causing compiler warning: "All paths through this function will call itself"

Tags:

swift

swift4.2

So I suddenly have this compiler warning that was not present on swift 3 or (I think) swift 4.0. the code below overloads the += operator to perform a vector increment:

public func += ( left:  inout CGVector, right: CGVector) {
  left += right
}

and produces the warning, I am puzzled can anyone shed light on why the warning is thrown and what is wrong?

like image 260
CodeSpringsEnternal Avatar asked Jan 29 '26 08:01

CodeSpringsEnternal


1 Answers

When you do left += right, it calls the same function that you were defining. In other words, your operator overload function += ( left: inout CGVector, right: CGVector) will call itself in all times (infinite recursion). You are doing something like

func foo(String: bar) {
    foo(bar)
}

But just by replacing foo with +=, which is not logical. Xcode only gives you a warning now though, it is not an error that stops you from compiling. You probably have written this function wrong in the past (but the warning reminding you this was just added to the compiler).

You probably want something like this

public func += ( left:  inout CGVector, right: CGVector) {
     left = CGVector(dx: left.dx + right.dx, dy: left.dy + right.dy)
}
like image 50
Papershine Avatar answered Feb 01 '26 00:02

Papershine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!