Migrating to Swift 2

I was recently tasked with migrating an iOS codebase from Swift 1.2 to the latest Swift version, which at the time of writing is 2.1. Anyone else having to do this will no doubt, like myself, have had mixed results.

If your codebase is small, the Xcode migration tool should take care of most of it for you. However, if your codebase is more mature, you’re going to run into some issues!

Unfortunately for me, the app I was migrating fell in the “super mature” category. I still decided to run the migration tool and see how it coped – not well is the answer. It took about 20 minutes to run and the most helpful thing it did was update some Classes to new versions (e.g. Printable becomes CustomStringConvertible). It also changed some occurrences of “var” to “let”, which got rid of some of those pesky warning messages. But other than that, everything else had to done manually.

When trying to build my app, it instantly failed with hundreds of errors….

The first thing I noticed, were some new function signatures that now throw errors, a new feature of Swift. These new function signatures are basically there to say, “Hey, this function could make a boo boo, so you need to make sure you cater for this”. It’s actually quite straightforward to handle, take the example below:

If for some reason, you can guarantee a function will never fail, you can get rid of the do/catch block and simply write:

Note the difference here of “try!”, not “try”.

There was also an update to SCNetworkReacabilityFlags which means you can no longer compare it to an Int using the equality operator. Instead you now use the .contains() function to do the same thing. Where previously you would write something like:

You now achieve the same result by doing:

Excellent!

There are many more APIs that were updated, luckily for me these were the main and most frequently occurring ones I had to deal with.

Happy migrating folks.

Leave a comment