0
我正在重載(或者可能在這種情況下實現)一個類(不是結構體!)的+ =運算符。該操作修改了左側實例的狀態。我注意到我可以用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