This is the way for me to print out the memory address of Array, to understand the implication of copy-on-write behavior of struct.
struct Array
func print(address o: UnsafeRawPointer ) {
print(String(format: "%p", Int(bitPattern: o)))
}
var x = [1,2,3]
var y = x
// 0x600002654260
print(address: x)
// 0x600002654260 // x & y pointing to same address.
print(address: y)
x.append(4)
// 0x6000010504d0
print(address: x) // Address changed after mutation, to avoid sharing same copy as y
// 0x600002654260
print(address: y)
x.append(5)
// 0x6000010504d0
print(address: x) // Address remained after mutation
// 0x600002654260
print(address: y)
However, when I want to do the same study on generic Set, the previous way is no longer workable.
Generic struct Set
func print(address o: UnsafeRawPointer ) {
print(String(format: "%p", Int(bitPattern: o)))
}
var x : Set = [1,2,3]
var y = x
print(address: x)
print(address: y)
x.insert(4)
print(address: x)
print(address: y)
x.insert(5)
print(address: x)
print(address: y)
I am getting the following error when calling print
cannot convert value of type 'Set' to expected argument type 'UnsafeRawPointer'
I had tried withUnsafePointer. But I suspect withUnsafePointer is not giving correct result. I am expecting both x and y should be pointing to the same address.
var x : Set = [1,2,3]
var y = x
// 0x000000010467c090
withUnsafePointer(to: &x) {
print("\($0)")
}
// 0x000000010467c098
withUnsafePointer(to: &y) {
print("\($0)")
}
What is the correct way to print address for generic struct Set, to understand the implication of copy-on-write behavior?

