Version number comparison – the right way

Version number comparison is often needed during app development. Whether you’re checking for an app upgrade, file/payload version or something else, you need a reliable way to see if two version numbers are the same, or one is greater or lower than the other. In software development version numbers are usually formatted as major.minor[.maintenance/fix]. Usually developers use the String compare API provided in the iOS SDK, and pass the numeric option of comparison. This is simple enough, but unfortunately, it will not always work.

The compare API works fine if you try to compare e.g. “1.0.1” and “1.0.3”, but the problems occur for comparisons of the same versions e.g. “1.0” and “1.0.0”. In this case you’d get that version 1.0 is lower than 1.0.0.

The right way to compare versions is to check each component of the version number with the implicit value 0 if the two versions are not of the same length. I created a Playground with this implementation. It also shows examples of different version comparisons and issues with the compare method.

You can find the Playground with these examples on my GitHub repo: https://gist.github.com/lukagabric/dbd61e73b76c8338af4b15995aab161e

I hope you liked this blog post and I’d appreciate if you followed me on Twitter

Related Post

Remember to share...Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *