[swift-users] Extracting arbitrary types (e.g. UInt16) out of Data

Rick Mann rmann at latencyzero.com
Sun Jun 25 19:37:16 CDT 2017

I continue to struggle with the "proper" and most efficient way to do things with Data.

In this case, I have a set of bytes received over a serial port in a Data. The last two bytes are a (big- or little-endian) UInt16 CRC. However, there maybe an odd or even number of bytes in the Data before these last two bytes, so I can't just use withUnsafePointer<UInt16>.

I'd also like to avoid unnecessary copying of the data. All of it is immutable for the purposes of this problem.

How can I get the UInt16 that starts at byte X in a Data? Same goes for Double or Int32 or whatever.

If the endianness needs to change, I can do that swapping after I've gotten the typed value out.

Rick Mann
rmann at latencyzero.com

More information about the swift-users mailing list