Compressing a Swift array

Suppose you have an array of values in your Swift app and you need to compress it to a smaller size, with the intention of making it occupy less memory. If the array contains many consecutive repeated values it could be compressed by only including a repeated value once, and tracking the number of consecutive occurrences for that value.

How might that code work? What about the code to decompress an array, how can that be implemented in Swift?

If you are interested in figuring this out yourself, I posted a gist that you can use as a starting point to test your code:

My solution is shown below. It uses some slick Swift goodness, such as a where clause, the flatMap method, and tuple decomposition.


The full source code is available, as a playground, here:

Happy Swifting!

About Josh Smith

Josh Smith is a musician at heart, and a software developer by obsession. He lives in Arizona, plays classical music on the piano, jazz on the guitar, and enjoys brutally long rides on his bicycle. He has a wonderful wife & son and thinks that, in general, life is good.
This entry was posted in Swift and tagged . Bookmark the permalink.

1 Response to Compressing a Swift array

  1. Pingback: Dew Drop – November 27, 2015 (#2140) | Morning Dew

Comments are closed.