I wrote the following code in Xcode to try and prove copy on write in Swift:
func print(address o: UnsafeRawPointer) {
print(o)
}
func longStringMemoryTest() {
var longStr1 = "abcdefghijklmnopqr"
var longStr2 = longStr1
print(address: longStr1)
print(address: longStr2)
print("[append 'stu' to 'longStr2']")
longStr2 += "stu"
print(address: longStr1)
print(address: longStr2)
var test = "abcdefghijklmnopqr"
print(address: test)
print("[Fin]")
}
However, the console always prints the same address for longStr1 and longStr2, even though longStr1 has a value of "abcdefghijklmnopqr" and longStr2 has a value of "abcdefghijklmnopqrstu". I can't figure out what I'm missing in this code. Can you explain how to prove copy on write for strings in Swift and why the address is always the same for longStr1 and longStr2?

Short Answer
You have nothing to prove because
Stringsupports copy-on-write from the documentation and it works under the hood. For instance, we can find the following in the header ofString.swiftsource file:Long Answer
First of all your code has a mistake:
Two different variables with different values have the same address! To fix the issue you should pass them as in-out parameters (like references) to get valid addresses:
Now it works right, but:
Variables have different addresses after the assignment because they are still allocated different parts of the stack memory for
Stringstructs. But at the same time they can share the common data becauseStringworks like a wrapper around a memory buffer.We can access to the internal String's buffer by the following key path
a._guts._object.nativeUTF8Startwithlldbso let's try that in XCode Console while debugging line by line:This test shows how copy-on-write works with
Stringin action.