After watching build better apps with value type . In the photoshop example they made, they said that
the only thing that gets copied in the two instances of that diagram are the tiles that contain the person’s shirt. So even though I have two distinct documents, the old state and the new state, the only new data that I have had to consume as a result of that is the tiles contained in this person’s shirt.
So I begin to wonder how would these two array in memory looks like. So I do a little experiment.
struct Test {
var i: Int
var j: Int
}
var valueArray = [Test(i: 1, j: 9), Test(i: 2, j: 7)]
var valueArray2 = valueArray
When I print valueArray and valueArray2’s address, they are not the same.
“Maybe they implement this by store pointer in array?”
But when I print memory content using lldb , they are actually just 4 Int (1,9,2,7).
So I am confused, I haven’t even change the array yet. And they seems to make a copy of entire array? So where did I misunderstand?
The function I used to print struct’s address is by using the method provided by @nschum in this question.
func address(o: UnsafePointer<Void>) {
let addr = unsafeBitCast(o, Int.self)
print(NSString(format: "%p", addr))
}
This is not a duplicate question of this question. I am asking about language feather and the other one is about programming skill.
2
Answers
Okay, I did many experiment and finally figured out.
&
to get array address because once we do that , Swift will copy the array to better interact with C, use&
get object's address that adjacent to array and do the math instead. Or use lldb instructionframe variable -L
I actually write my first blog for this.
After your comments and getting a better understanding if this, I loaded it up in a playground and it seems to be working as expected
original answer for reference
The thing to remember with this is that structs are basically chunks of data in memory. When you create the valueArray, a chunk of memory is being set to value it’s assigned
When you create valueArray2, you’re creating a new instance of the struct, which means it will have a brand new chunk of memory, and you’re then setting the value of that new chunk of memory to the same value of the chunk of memory from the valueArray. This results in a copy of the data in two different memory locations.
This is in contrast to an object, in which case valueArray would be a pointer to a chunk of memory, and when you create valueArray2 it would be creating a new pointer to the same chunk of memory.