It’s The Little Things That Matter…

Since I started at Code Fellows as a Sr. iOS Engineer / Instructor a few month ago, I decided I am going to write an article a week on topics I find interesting when it comes to Swift, Objective-C, or iOS in general.

This week I would like to simply take the time to appreciate the awesomeness of Swift – but not just any version of Swift, I would like to talk specifically about Swift 2.0.

Granted, it’s the second major release of the language (although some can argue, and rightfully so, that Swift 1.2 was somewhat a major release), it’s already on par with Objective-C which, as of writing this article, is stable at version 2.0… Let me get off track for a second please. Every time I mention Objective-C, I feel a bit nostalgic. I started developing in Objective-C years ago… days before ARC and all of the out-of-the-box features we, iOS developers, enjoy today (thank you Apple). Objective-C will always be part of my developers vocabulary.

Anyway, Swift 2.0…

When it was first released, I was blown away by its simplicity, or just blown away it was released in the first place :] However, after writing a few things I quickly realized that the simplicity and safety came at a price of what many refer to as the “Pyramid of Doom”. Despite optional chaining released in Swift 1.2, the “Pyramid of Doom” still lingered around in various forms – not only when serializing JSON.

Apple solved this in Swift 2.0 with guard statements. Let’s take a look at examples of how guard can beautify and simplify your code…

In the example above, you can clearly see me using the optional chaining and yet the code / function still feels too busy. Here is how this same function would look like using guard statements:

As you can see there are no more “if” statements; we are simply guarding a condition and executing code if previous line succeeds.

It’s important to note that “if let” still has a very important role to play. Here is an example:

If the number variable is not initialized, nothing below the initial guard statement will be executed. In our case the function self.update() is out of luck. Here, it would make much more sense to use the if let statement to execute logic on true or false while allowing other code (self.update()) to execute.

Use guard if you are writing a function whose execution depends on the above code to succeed. My first example is in fact a great example… if the function implements conditional state, if let is the way to go.

I realize that this a relatively simple example, but you get the gist of it. It’s the small things in Swift 2.0 that make all the difference in the world.

It’s The Little Things That Matter…