简体   繁体   中英

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM