I have observed that when we do change a property value of struct, then a new struct object is created.
struct StructureTest {
var i: Int
mutating func changeValue(_ val: Int) {
i = val
}
}
var st = StructureTest(i: 10) {
didSet{
print("struct changed")
}
}
print("before: \(st)")
st.changeValue(20)
print("after: \(st)")
Output:
before: StructureTest(i: 10)
struct changed
after: StructureTest(i: 20)
Main thing I have noticed that after changing it's property value. A new struct object is created and assigned to var st
.
I do know what are "value types" and what is "copy on assign" feature.
But I am unable to understand that why is it happening here? Maybe I am missing something here? Let me know if you do know the reason for this new struct instance creation.
Along side with this I have observer one more thing that:
If I have a array of structs. Like as:
struct StructureTest {
var i: Int
mutating func changeValue(_ val: Int) {
i = val
}
}
var arrStructs = [StructureTest(i: 10), StructureTest(i: 20)] {
didSet {
print("arrStructs changed")
}
}
arrStructs[0].changeValue(30)
Output:
arrStructs changed
I am unable to understand that why is array modifying?
As much I can understand from "copy of write" feature on value types. It should happen when an array is modified and array capacity requires to create a new array but in this case array modification reason is not clear to me.
Do let me know If you do know the reason behind that or if you can provide me any reference for clarification.
Sorry for my grammatical mistakes. Hope the essence of problem is clear to you.