How to find out the memory area of an "optional" in swift?

Viewed 83

I am studying CoW. I understand that under the hood of an array and dictionary, the CoW works.

To check this, I looked at the memory area through the print.

var array1 = [1,2,3] 
array1.withUnsafeBufferPointer { (point) in
    print(point)      // 0x00006000006080e0
}
var array2 = array1 //  0x00006000006080e0
array2.append(4)   // 0x0000600002351ba0 <- changed

How can I see the memory area of an optional type? At the conference I'm watch, the author said that under the hood of the optional, the CoW also works and I want to check it out.

.withUnsafeBufferPointer - for optional types does not work!

var optionalInt: Int?
optionalInt = 1                 // memory area?
var optionalInt2 = optionalInt // memory area?
optionalInt2 = 2              // memory area?
2 Answers

You need to use withUnsafePointer(to:).

var optionalInt: Int?
print("optionalInt = \(optionalInt)")
withUnsafePointer(to: optionalInt, { pointer in
    print("optionalInt: \(pointer)")
})
optionalInt = 1
print("optionalInt = \(optionalInt)")
var optionalInt2 = optionalInt
print("optionalInt2 = \(optionalInt)")
withUnsafePointer(to: optionalInt2, { pointer in
    print("optionalInt2: \(pointer)")
})
optionalInt2 = 2
print("optionalInt2 = \(optionalInt)")

Output:

optionalInt = nil

optionalInt: 0x00007ffee58ede90

optionalInt = Optional(1)

optionalInt2 = Optional(1)

optionalInt2: 0x00007ffee58ede28

optionalInt2 = Optional(1)

As David suggested - the right decision. But you can run into a bug. And all your optionals will point to the same region in memory. This is what happened to me:

enter image description here

To avoid this, check like this:

func pointer(object: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer {
    return object
}

var optional1: Int?
var optional2: Int?

print( pointer(object: &optional1) ) // 0x0000000108f68090
print( pointer(object: &optional2) ) // 0x0000000108f680a0
Related