Reputation: 5533
Why can't the properties of a value type be modified from within its instance methods?
I have already read Apple's Swift documentation, which does not provide an exact explanation as to WHY. Yes I know that value types are copied when passed around, but what does that have to do with methods not being able to modify instance properties. However, these properties can be modified from the outside the struct.
Also, I found one or two posts similar to this one on here. Unfortunately, the answers on those are still ambiguous.
Upvotes: 0
Views: 57
Reputation: 437
If you want to modify an instance of a struct you must use mutating keyword in front of the function definition.
struct Point {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
Upvotes: 2