how to overload an assignment operator in swift

That’s not possible – as outlined in the documentation:

It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded.

If that doesn’t convince you, just change the operator to +=:

func +=(left: inout CGFloat, right: Float) {
    left += CGFloat(right)
}

and you’ll notice that you will no longer get a compilation error.

The reason for the misleading error message is probably because the compiler is interpreting your attempt to overload as an assignment

Leave a Comment