2016-08-16 41 views
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 

回答

1

在這種情況下的恆定let是參考aMyClass對象它指向。它阻止你能夠做到這一點:

let a = MyClass() 
a = MyClass() //redefinition not allowed 

,並不能保證有關,不過該對象的成員的恆常什麼。類/對象的存在是爲了模擬不斷變化的數據,標記方法作爲變異會有點乏味,因爲最終這就是他們一般應該做的。

如果您想要控制突變,您應該使用結構。