Why Swift Flies for iOS Developers

Now that the dust has settled somewhat on Swift, the new language on the block for developing iOS and OSX applications, we take a look at its impact and improvements over its predecessor, Objective-C. Apple claims Swift to be a modern, safe, and powerful language for developing for iOS and OSX. Just how powerful is Swift compared to the venerable Objective-C? And how does it make developing applications easier and safer? In this article, I will walk you through some of the important features in Swift and how it improves on Objective-C. In a follow up article, I will show you how you can use Swift and Objective within the same project.

Why is Swift Important?

While Apple intended to use Swift as the de facto language for writing iOS and OSX apps, its birth definitely has an impact on the computing world and the long-term future of programming languages.

With Swift, Apple aims to address the number one complaint of iOS and OSX developers: that Objective-C is showing its age and is a difficult-to-learn language, especially with its arcane syntax, and memory-management pitfalls. Developers coming from modern languages like C# and Java often struggled with learning Objective-C, and this is something that Apple desperately needed to address in the long term if it want to maintain iOS as an enticing platform for developers.

As you will see in this article, Swift addresses a lot of the shortcomings in Objective-C, making it far simpler, even for beginners, to come up with a simple app in a short amount of time. With the new, interactive Playgroundtool in Xcode 6, learning Swift has never been easier. And this is where Apple is spot on – by making it easy to learn and test the code, Apple hopes to make the language more approachable, and hence encourage a new group of self-taught programmers to develop the next generations of apps. Playground allows you to type in the code and see the result instantly. Make a change to your code and your program will immediately change: instant gratification!


Instant gratification with the interactive Playground tool (source: Apple)

Developer’s Love it!

Languages come and go, and with Swift, there is a huge motivation for developers to learn the language. With many languages, one might spend some time to learn the new syntax, and often the next thing that happens is that interest is lost as the developer moves on to other more interesting projects. With Swift, more so than most other languages, there is a huge enticement to get onboard: the lure of the AppStore and the 800 million iOS devices that are waiting to run your latest creation.

Not only must a language be able to address all the key computing challenges, it must be easy to learn, and there must be an inherent appeal to pique developers’ interest. In addition, there needs to be an abundance of innovative tools to ensure that the language is accessible and fun.

Apple is ticking all the right boxes with Swift, and developers loved it right from the start. With the first Swift app publicly released on 2nd June 2014, it didn’t take long for developers to line up. Within hours, Flappy Swift, a Flappy Bird clone, was written in Swift and released into the wild. Underscoring the simplicity of the language, the developer, Nate Murray, saidIt took me about four hours to read the e-book on programming Swift and put it together“.


Flappy Swift in action, with an excerpt of its Swift code behind (source: Flappy Swift github)

Wider impact of Swift

With the release of Swift, all eyes are now on Google, who’s Android platform, in contrast to iOS, is still reliant on a language that it does not own: Java. Since 2010, Google has been embroiled with Oracle in a legal battle over the use of the Java APIs in Android, the ultimate outcome of which will have a big impact on both Android and software development in general. It could indeed be hugely expensive for Google, and at the same time stymie the evolution of Android. Having its own Swift might not be a bad thing for Android.

And while Java is not really comparable with Objective-C in terms of developer-unfriendliness, Swift has elicited many a green-eyed side-glance from Android developers. Proponents of Dart (Google’s own Web programming language) have been suggesting Google adopt its own language for Android, where doing so will give it more control over the progression of the language and platform. Indeed, Google may be forced to do so very soon, as they have already witnessed throngs of mobile developers moving to other toolsets (such as Xamarin, PhoneGap, and Titanium) that do not use native languages such as Objective-C and Java.

As pointed out by Christian Grobmeier, Swift “looks pretty similar to Dart actually”. If iOS developers can benefit from more modern programming concepts, then why not Android developers too?

Swift: Objective-C without the C

So exactly how has Apple achieved these improvements? During its announcement at WWDC 2014, Swift was described as Objective-C without the C. In the following sections we take a look at some specifics of exactly how Swift makes iOS app development easier. And what better way to do it than by looking at some of the differences between Objective-C and Swift.

Type Inference

In Objective-C, you have to explicitly specify the data type of variables when you declare them:

In Swift, the compiler will automatically infer the type of variables/constants that you are declaring:

In Swift, you use the let keyword to declare a constant and the var keyword to declare a variable.

Of course, you can also explicitly declare the type of a variable/constant. This is especially useful if you:

  • Are not assigning an initial value to a variable during declaration time, or
  • Do not like the default data type inferred by the compiler

For example, the following example declares score to be of type Float and then assigns it a value:

You can also rewrite the above by combining the two statements:

The above example is also useful because you explicitly declare score to be of type Float. If you simply let the compiler infer the type, score would be inferred to be of type Double, rather than Float:

Tuples – Compound Variables

In Objective-C, a method can return at most one value. If you want to return multiple values, you can resort to a number of ways:

  • using inout parameters to return values after a method call
  • returning objects or structures containing the values you want to return

In Swift, there is a neater way – tuples. A tuple is an order collection of values. The values inside a tuple can be of any type and need not be of the same type. The following shows an example of a tuple:

To access the individual elements inside a tuple, you can use its index, starting from 0, like this:

The following function returns a tuple:

When you call the function it returns a tuple, which you can then access, its individual elements:

Improved String Handling

One of the key complaints by programmers learning Objective-C for the first time is that of string handling. The class dealing with strings in Objective-C is the notorious NSString class. To relive the horror, consider the case that you want to create a string containing the value of a number. You have to do the following:

You have to use the stringWithFormat: method of the NSString class to create a string that combines some text with a number. The nightmare continues if you try to concatenate two strings:

With Swift, strings handling is now much more straightforward and easy. The above could be rewritten using the String type in Swift, like this:

The () syntax is know as string interpolation. Put any variable within the parentheses and it will return a string.

One added bonus is that all the APIs in the NSString class that you have painstakingly taken years to learn and master are available in Swift – by type casting a String instance to an NSString object:

New Types – Optionals

Swift introduces the new optional types. An optional type means that a variable can either have a value, or nil if it does not have one. To understand the rationale for optionals, consider the following example in Objective-C:

In the above you are trying to convert the strNum variable to an integer value. Because the strNum variable contains a comma in it, the conversion incorrectly returns 2 instead of the expected 2500. This will cause the statements after it to incorrectly perform its calculation. Ideally, the integerValue property of the NSString class should return a nil to indicate that the number cannot be converted to an integer value correctly.

In Swift, the above statements would look like this:

However, note that since the conversion from 2,500 fails, the toInt() method does not return a 2. Instead it returns a nil. And because num can now either contain a valid integer value, or nil, the type of num is now inferred to be Int?. The ? indicates that num is of type Integer optional.

To access the value of num, you need to first of all check if it is a nil. Only if it is not a nil can you access it by appending the ! character to the end of num, like this:

Besides using type inference, you can explicitly declare a variable to be an optional type. For example, the following statement declares description to be a String optional:

You can assign a value to an optional type:

Or set it to nil:

When dealing with optional types, you should check that it is not nil before accessing it value or methods/properties. For example, you need to ensure that description is not nil before calling its properties, such as uppercaseString:

Because checking an optional for non-nil is so common, you can actually use the following shortcut:

The above statement reads: “If description is not nil, then call its uppercaseString property”.

Improved Enumerations

In Swift, enumerations are much improved. Consider the following enumeration definition in Objective-C:

To use the BagColor enum, you declare a variable of BagColor, and then assign it a value within the enum:

The first problem is that you often have a lot of difficulty knowing the members in an enumeration. Code completion in Xcode could not help without needing you to read the definition of the enumeration. Second, often you need to save the value/print the value of an enumeration type so that you can persist the data. For example, you might want to print out the color of the bag as “B” if it is Black, “W” if it is White, and so on. In Objective-C, you often have to implement your own method to do this, like this:

You then have to pass in the enumeration type into this method in order to get its string equivalent:

In Swift, you could simply declare the enumeration as follows:

To print out its string equivalent, use the rawValue property:

To convert a string back to its equivalent enumeration value, use the rawValue: method:

Note that colorOfSecondBag is declared to be of type BagColor optional. This is because there is a possibility of passing in a string (such as “P”) that does not match any of the colors in the enumeration.

Switch on Steroids

The Switch statement in Swift in now on steroids. To understand why I said so, read on.

First, there is no more implicit fallthroughs – after each case is matched, it automatically exits the switch statement.

With this enhancement, it eliminates a lot of bugs that we inadvertently introduced into our Objective-C code, and indeed many other languages, simply by forgetting to insert the break keyword into the end of each case.

You can also match characters in a Switch statement:

In certain conditions, fallthroughs are still useful. Swift supports explicit fallthroughs using the fallthrough keyword:

You can also match ranges in a Switch statement:

Matching ranges also applies to tuples:

You can perform conditional checking within a case by performing value bindings in a Switch statement:

You can even specify a where clause within a case!

Summary

In this article, we’ve looked at a variety of features in Swift that makes it a modern and safe language. It is clear that Swift is a much more developer-friendly language than Objective-C, and has lowered the barrier-to-entry for iOS development.

We’ve also tried to take a look at Swift in the broader context of app development in general, and to put it in perspective with other platforms. Traditionally, Android has had a somewhat lower barrier-to-entry for developers, with more development tools and platforms available to use. The introduction of Swift has leveled the playing field to a certain extent, and has arguably tipped the balance a little too. However, while serious Android developers are unlikely to abandon the platform altogether simply because another platform has better development tools, the draw of well thought-out and easy-to-use tools should not be underestimated.

It also begs the question of whether Google has plans to launch new Android tools. As many developers have suggested, Google’s Dart programming language might make a good fit for Android, and shares at least some of the beneficial simplicity of Swift.

Leave a Reply

Exclusive tips, how-tos, news and comment

Receive monthly updates on the world of mobile dev.

Other Products

Market leading device intelligence for the web, app and MNO ecosystems
DeviceAtlas - Device Intelligence

Real-time identification of fraudulent and misrepresented traffic
DeviceAssure - Device Verification

A free tool for developers, designers and marketers to test website performance
mobiReady - Evaluate your websites’ mobile readiness

© 2024 DeviceAtlas Limited. All rights reserved.

This is a website of DeviceAtlas Limited, a private company limited by shares, incorporated and registered in the Republic of Ireland with registered number 398040 and registered office at 6th Floor, 2 Grand Canal Square, Dublin 2, Ireland