August 20, 2014

Shortening a UUID / GUID in Swift

Universally Unique Identifiers (UUID, also known as a GUID on Windows) are a helpful standard for identifying things uniquely among the throng. To make sure that for all intents and purposes each UUID is unique it has to be 36 characters long. When transferred over a network on a large scale, these lengthy identifiers will eat up bandwidth. In the spirit of optimization, what's a good strategy to compress them for transit?

Jeff Atwood has a helpful article on the topic. Spoiler alert: his conclusion is that ASCII85 encoding can be used to compress a UUID down to 20 characters.

I implemented a base64 solution as an excuse to get better acquainted with Swift. The downside of using base64 is that it yields a 22 character compressed UUID. The upside is that a base64 implementation is built into Cocoa / Cocoa Touch. If you go with ASCII85 you'll have to roll your own implementation.

Please keep in mind that additional changes will need to be made to this solution if the intent is to pass the compressed UUID as part of a url string (eg. '+' and '/' characters, etc will need to be dealt with). Try it out for yourself in a Swift playground!