Pros and cons of Unmanaged, UnsafePointers and Data?

UnsafeMutableRawPointer vs Data?

These offer completely different semantics:

  • UnsafeMutableRawPointer is roughly equivalent to a C buffer pointer and length. It’s pretty much completely unsafe [1].

  • Data is a value type that uses CoW under the covers.

Or Data vs Unmanaged?

Unmanaged is a mechanism to work with reference counts directly. Most Swift code uses automatic reference counting (ARC), which means the compiler takes care of the reference counts for you. Unmanaged is useful in situations where you’re escaping the ARC world in order to interoperate with manual retain/release environments, like a C library.

You use passRetained(…) when you need to pass an unmanaged value to C (for example) and you want to increment the retain count on that value. This is useful for escaping contexts, with the obvious caveat that you have to decrement the retain count at some point.

You use passUnretained(…) when you need to pass an unmanaged value to C and don’t want to retain that value. This is useful for non-escaping contexts.

There are similar takeRetainedValue() and takeUnretainedValue() routines for when C is passing you an unmanaged value and you want to bring it back into the ARC world.

Finally:

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

[1] Except that it does bounds checking.