简体   繁体   English

可以在Swift中重载+ =运算符吗?

[英]Is it possible to overload += operator in Swift?

Is it possible to overload += operator in Swift to accept for example CGFloat arguments? 可以在Swift中重载+ =运算符来接受例如CGFloat参数吗? 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. 运算符+ =不需要为CGFloat参数重载,因为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. 这失败了,因为我无法放弃let XCode显示的错误let我感到困惑。

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. CGFloat+=运算符已经可用,所以你只需要使用它 - 你唯一能做的就是覆盖现有的运算符,如果你希望它以不同的方式运行,但这当然是不鼓励的。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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