【发布时间】:2016-08-16 01:34:57
【问题描述】:
我正在重载(或者在这种情况下可能实现)一个类(不是结构!)的 += 运算符。该操作修改左侧实例的状态。我注意到我可以使用let 声明左侧元素而不会出现任何错误(并且由于它是类的实例,因此它的内部状态会随着操作而变化)。这当然是不希望的,并且应该导致编译时错误。有没有办法将重载的运算符声明为左侧元素的变异?
class MyClass {
static func +=(lhs: MyClass, rhs: MyClass) {
lhs.fu(rhs) // fu() changes internal state of lhs
}
}
let a = MyClass()
let b = MyClass()
a += b // this is legal but shouldn't be, since instance 'a' will
// have a different internal state after the concatenation
【问题讨论】:
标签: swift operator-overloading swift3