2

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 2

3

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)

2
  • I think I am really bad at documentation. How did you find it? Give advice for the future.
    – errorka
    Aug 4, 2021 at 16:14
  • 2
    @errorka I knew about its existence, so didn't have to look for it. However, if you check the documentation of withUnsafePointer(to:), you'll find a whole Manual Memory Management category under the documentation of the Swift Standard Library. Aug 4, 2021 at 16:16
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
1
  • 1
    You should never check memory in a playground. Playgrounds are not optimised and work quite differently from real Swift app/framework projects, so you should always use an actual Xcode project for debugging memory issues. Aug 5, 2021 at 7:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.