Best practice for parsing heterogeneous types from Data (in Swift 5)

It's a shame Data is so complex and a lot of the safe solutions are so convoluted. I wish we had a more basic array-of-bytes data structure in standard lib with convenient low level methods like (de)serialization of ints and simpler interop with C.

Does my extension below still capture what you were trying to
demonstrate about moving up in abstraction?

Yep. I have written code like that myself (-:

I had to insert a .reversed() to your example code in order for it
to correctly parse little endian integers.

Be careful here. My code used big endian because that’s the documented order for 'icns' data. If you always reverse, you’re assuming little endian. That may be the right thing to do in your case, but if your goal is to support host endian — that is, big endian on big-endian architectures, little endian on little-endian ones — you’ll have to conditionalise that reverse.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

1 Like

It's a shame Data is so complex and a lot of the safe solutions are so
convoluted. I wish we had a more basic array-of-bytes data structure
in standard lib with convenient low level methods like
(de)serialization of ints and simpler interop with C.

It’s not easy to meet these requirements. On the one hand, you’re saying that Data is too complex, and on the other hand you’re asking to make it more complex by adding support for serialisation of common types. Also, from your other posts, I know that you’re very concerned about performance, and that’s often at odds with convenience.

However, I am sympathetic to your goals here, and I’m not the only one. If you search Swift Forums for data standard library, you’ll see multiple evolution threads about moving Data to the standard library. And the SwiftNIO folks created ByteBuffer because it offers specific advantages over Data.

If you want to help make this wish a reality, I recommend that you engage in Swift Evolution.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

Terms of Service

Privacy Policy

Cookie Policy