Is it possible to overload += operator in Swift to accept for example CGFloat
arguments? If so, how?
My approach (below) does not work.
infix operator += { associativity left precedence 140 }
public func +=(inout left: CGFloat, right: CGFloat) {
left = left + right
}
The coding approch above actually works. Please see my answer below for explanation why I thought it did not.
I am sorry, my bad. The operator += does not need to be overloaded for CGFloat
arguments as such overload is included in Swift. I was trying to do something like
let a: CGFloat = 1.5
a += CGFloat(2.1)
This failed because I cannot asign to let
and the error displayed by XCode confused me.
And of course, approach like in my original question (below) works for overloading operators.
infix operator += { associativity left precedence 140 }
public func +=(inout left: CGFloat, right: CGFloat) {
left = left + right
}
Please feel free to vote to close this question.
The +=
operator for CGFloat
is already available, so you just have to use it - the only thing you can do is override the existing operator if you want it to behave in a different way, but that's of course discouraged.
Moreover, the +=
operator itself already exists, so there is no need to declare it again with this line:
infix operator += { associativity left precedence 140 }
You should declare a new operator only if it's a brand new one, such as:
infix operator <^^> { associativity left precedence 140 }
However, if you want to overload the +=
operator for other type(s) for which it is not defined, this is the correct way:
func += (inout lhs: MyType, rhs: MyType) {
lhs = // Your implementation here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With