DudeOnRock DudeOnRock - 1 year ago 98
Swift Question

Declare overloaded += operator as mutating?

I am overloading (or maybe implementing in this case) the += operator for a class (not a struct!). The operation modifies the state of the left-hand-side instance. I noticed that I can declare the left-hand-side element with

without any errors (and since it is an instance of a class, it's internal state changes with the operation). This of course is undesired, and should result in a compile-time-error. Is there a way to declare the overloaded operator as mutating to the left-hand-side element?

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

Answer Source

The let constant in this case is the reference a to the MyClass object that it points to. It prevents you from being able to do this:

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

It does not guarantee anything about the constancy of the members of that object however. Classes/objects exist to model constantly changing data, marking methods as mutating would be a bit tedious, because ultimately that's what they're supposed to do, in general.

You should be using structs in cases where you want controlled mutation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download