Dan Rosenstark Dan Rosenstark - 1 year ago 92
Swift Question

UnsafeMutablePointer<UInt8>: What's the risk?

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


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
... is this the best thing for Swift interop?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download