Dan Rosenstark Dan Rosenstark - 5 months ago 13
Swift Question

UnsafeMutablePointer<UInt8>: What's the risk?

I'm receiving one of these in a callback from an Objective-C library:

UnsafeMutablePointer<UInt8>


I'm able to parse it. I'm also able to create one to send it back to the library, but: What are the risks of working with the "unsafe" type? How do I avoid those risks?

Also, the Objective-C library is using
uint8_t *
which bridges to Swift as this
UnsafeMutablePointer<UInt8>
... is this the best thing for Swift interop?

JAL JAL
Answer

UnsafeMutablePointer is how you represent a C pointer in Swift. It's unsafe because the underlying memory the pointer points to could change at anytime without the Swift pointer knowing. It also has no information about the size of the memory block that it points to (thanks Martin).

If your library requires you to use C types, in this case a pointer to a uint8_t, then you must use UnsafeMutablePointer. Otherwise I if you just want to represent an array of numbers I would wrap all of the uint8_t types in an NSArray as NSNumber types (or NSData if you are pointing to a byte stream) for easier bridging.

You can avoid these risks by dereferencing the pointer (if it is non-nil) and copying the value stored at the pointer to a variable in your Swift application.

Comments