Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload += operator in Swift?

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
}

(Edit) Important:

The coding approch above actually works. Please see my answer below for explanation why I thought it did not.

like image 319
Rasto Avatar asked Nov 04 '14 23:11

Rasto


2 Answers

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.

like image 186
Rasto Avatar answered Oct 05 '22 22:10

Rasto


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
}
like image 34
Antonio Avatar answered Oct 05 '22 22:10

Antonio