struct Test {
var a: Int
func changeA() {
a = 10
}
}
var testInstance = Test(a: 10)
testInstance.a = 1
I understand, Structs are immutable, nonetheless the Swift compiler allows me to change Property "a" to 1, after it was already initialized to 10, were Structs immutable? why this is allowed?
If the Swift compiler allows to change property "a" from the instance, why it doesn't allow to have the method "changeA" to modify "a" from within the Struct without adding the "mutating" modifier? It seems it is allowed to modify the property from the instance, but not from a method within the Struct, why?
These are more conceptual questions, I fully understand that I can add "mutating" in front of the method and it will compile, but why I have to do that, if by default I am allowed to modify the property from outside the method after initialization, why the extra level of rigor with "mutating" to modify a property, that it is already declared as "var"?
I am very much interested in the theory and concepts behind Struct's immutability.
CodePudding user response:
You have variable and constant variables. Variable is marked with var
, constant variables is market with let
.
So you are not able to modify properties of constant let
s and not able to call mutating methods. So to mark method that are not allowed for constants, they are notated with mutating
CodePudding user response:
Structures are value type. When you create an instance from structure , it creates copy .
in function createA
without mutating , it works like self.a = 10
. If swift allow that , when you call this function from any instance , it will effect the main structure properties , gonna run like reference type.Lıke
struct Test {
var a: Int = 3
func changeA() {
a = 10
}
}
var testInstance = Test()
testInstance.changeA()
//testInstance.a = 10
var testInstance1 = Test()
//testInstance1.a = 10
var testInstanc2 = Test()
If mutating doesnt exist. changeA() works like class and testInstance1.a
would not be 3 anymore .
When you add 'mutating'
to your function . It not use self
it actually create a new instance from self . Function actually work like
mutating func changeA() {
Test().a = 10
}
and when the method ends , its properties from within the method, and any changes that it makes are written back to the original structure when the method ends.
link here
Thats why we have to use mutating.