I'm not a Swift programmer, so I have no clue about the language. I'm just asking out of curiosity.
I came across a language construct where self
inside a mutating function gets assigned a new value like in the function moveByAssigmentToSelf
in the example below.
struct Point {
var x = 0.0
var y = 0.0
mutating func moveByAssigmentToSelf(_ deltaX: Double, _ deltaY: Double) {
self = Point(x: x + deltaX, y: y + deltaY)
}
mutating func moveByMutatingMembers(_ deltaX: Double, _ deltaY: Double) {
self.x += deltaX
self.y += deltaY
}
}
Coming from a C/C++/Java/C# background I think of self
as a pointer (address) to the (start of) the struct value somewhere in memory (e.g. on the stack).
To me, assigning to something that should be equivalent to this
in a C++ struct looks very strange. AFAICT, the function moveByMutatingMembers
should have an observationally equivalent effect and would be the natural thing to do in the C++/Java world.
Can someone explain to a non-Swift programmer what is the rationale / idea behind this concept?
All I can find in the language reference (the chapter on expressions) are the following vague statements: "In an initializer, subscript, or instance method, self refers to the current instance of the type in which it occurs." and "In a mutating method of a value type, you can assign a new instance of that value type to self."
What I'm trying to understand is why is that assignment a good idea, which programming problems does it solve compared to the conventional solution?
In other words: Why does this make sense from a language-design perspective? Or: What would you lose if you had to do it the C++/Java way?
BTW, out of curiosity, I had a look at the Godbolt disassembly of this example and for my untrained eyes the output for moveByAssigmentToSelf
looks horribly inefficient compared to the alternative.