Technology

Some Reasons Why Swift is Better than Objective-C

8 Jan 2015 9:21am, by

Described as Obective-C without the C, Swift was released by Apple in 2014 and was met with mixed reactions. To existing Objective-C developers it’s a “who needs it?”, while to the millions who have struggled learning Objective-C it’s a breath of fresh air. Here I present a few cases to show why I feel that Swift as a programming language is superior to Objective-C.

Objective-C is nearly 25 years old and is best programmed by those with a ‘C’ mindset. For example to assign text to a string requires a pointer to a NSString, one of the built in types :

And that means you really need to know about pointers and memory allocation. Now the introduction of ARC (Automatic Reference Counting) simplified memory allocation as before that you had to do it manually, allocating it using retain and making sure it was freed up with release. Objective-C 2.0 also introduced a simpler literal syntax so instead of long cumbersome method calls, simpler code could be used. These two both assign true (YES) to a NSNumber.

So Many Files!

Standard C has distinct compilation units, each usually has a header file with a .h extension and a C file with .c. Objective-C is similar except the C file is .m not .c. Other programming languages such as Java, C#, even JavaScript and of course Swift manage with just one file.

The reason for the header file is when you are accessing variables, types or functions defined in another file. The .c or .m file has the body of the functions but the header file is where they are declared. Having to read separate header files slows compilation down. Swift only has the one declaration.

Swift

Swift has cherry picked many of the best features from other languages. Optionals are similar to nullable types in C#. Variable declaration is Pascal like except the var applies to every declaration. Overall it’s a quite elegant language and some of the features show some really good thinking. Readability is enhanced by a simplified syntax. Semi-colons are not needed to separate statements unless you want multiple statements on one line.

One of the best Swift improvements is with control flow statements like if, for, while and do-while. In C and many other languages, the block after the statement can be a single statement or a block inside braces. Programmers are often warned that single statements, not inside braces can lead to problems and 2014 saw a real doozy with the OpenSSL Goto error.

Despite the indentation, (this isn’t Python) the second goto is always executed thus skipping a load of checks and compromising SSL encryption. It was fixed in iOS 7.0.6 but had this been coded in Swift it would have caused a compile error. Apart from switch statements, all the others control flow features require braces and no single line statements are allowed.

So this is ok

But this is not and will generate a ‘Expected { after if condition’ error.

Static or Dynamic

Swift brings type safety to iOS development as the dynamic nature of Objective-C means the compiler can’t rely on knowing the type of methods at compile time. On the plus side you can add methods to existing classes at runtime and change the type of an instance but those come with a price; the runtime code has to do extra checking of the selector implementation and that adds extra code. The Swift compiler because of static typing can optimize calls and directly call the method or use a virtual table (a vtable).

Returning Data With Tuples

Objective-C has no direct support for tuples. These are a way of lumping two or three values in one place. A bit like a struct but simpler. Swift has added tuples, here’s one with a String and an Int.

The individual parts can be accessed by position so a.0 has the value “David” and a.1 is 40.

Where tuples really score though is in the return value for a function. Being able to return multiple values is very convenient with functions that compute multiple values or return an error code as well. The following example shows how to implement a function findpos that searches a supplied array and returns the position. The returned tuple is an optional tuple so that it can check for an empty array and returns nil in that case.

The ‘if var b =’ syntax means that if the call to findpos returns a non nil value then it declares a variable b and assigns the returned value to it.
The return value of findpos is an optional tuple but to access the tuple it must be unwrapped. This is done by the ‘if var b’ so that b contains the unwrapped tuple, not the optional.

This can take a bit of getting your head around. Consider this alternate code instead of the ‘if var b’.

Here b has the value of an optional tuple and to access the tuple part it needs to be unwrapped from the optional. You can do this manually by appending an exclamation mark so b! gives you access to the underlying tuple members. But that’s not good programming as it needed two unwraps. Hence the use of ‘if var b’ or ‘if let b’. Use ‘if let b’ if the returned value is never changed.

Strings

Swift strings are a significant improvement over Objective-C. No worrying about using a mutable or immutable string type, if you want a string you can change use var to declare it or use let for immutable. Concatening strings is as easy as

What’s not so obvious that I didn’t even have to declare the string type. The compiler inferred it was a string from the right of the =.

Swift strings support the full Unicode character set and can even be used in switch statements, neither of which works in Objective-C.

Conclusion

My aim hasn’t been to knock Objective-C which has been a very successful programming language given how many Apps have been developed with it just to show how Swift improves on it. I see Objective-C as a manual lawn mower where you sweat a lot but it gets the job done. Swift by comparison is like an electric mower and will reduce the amount of work needed. It also has better protection so you can’t slice off your fingers.

A newsletter digest of the week’s most important stories & analyses.

View / Add Comments

Please stay on topic and be respectful of others. Review our Terms of Use.