Objective C vs Swift

On June 2nd, 2014, Apple unveiled a brand – new object-oriented programming language: Swift, a replacement for Objective-C, which had been up to that point the standard programming language for OS X and iOS application development.

It was a bold move to outright change the main development language for such a popular platform; even so, our team responded to this news with huge enthusiasm and decided to switch to it in short order. And we’re not the only ones: Swift has received glowing praise for its simplicity and flexibility, and its adoption rate has skyrocketed.

After developing a couple of iOS applications with Swift, we decided to share our thoughts about some of the things we think make it easier and more enjoyable to program with. So here’s our top ten list of the biggest and most important differences between Swift and Objective-C!

(Feel free to use a playground to practice with the code snippets in this article. It’s always a good idea to explore new languages and frameworks!)

Swift vs. Objective-C: 10 Differences

1. Optionals
2. Control Flow
3. Type Inference
4. Tuples
5. String Manipulation
6. Guard and Defer
7. Functional Programming Patterns
8. Enumerations
9. Functions
10. Do Statement

1. Optionals

Optionals are a concept which doesn’t exist in C or Objective-C. They allow functions which may not always be able to return a meaningful value (e.g. in the event of invalid input) to return either a value encapsulated in an optional or nil. In C and Objective-C, we can already return nil from a function that would normally return an object, but we don’t have this option for functions which are expected to return a basic type such as int, float, or double. Observe:

The Int function in this case returns an optional containing the int value 512, as expected. But what happens if we try to convert something like “Hello” instead? In that case, the function will return nil, as explained above:

As you may already know, in Objective-C, if you call a method on a nil pointer, nothing happens. No compile errors, no runtime errors, nothing. This is a well-known source of bugs and unexpected behavior, and overall frustration: the lack of feedback means developers are forced to hunt down the source of these errors all on their own.

With Swift, you don’t have worry about this:

The compiler itself will raise an error, since x right now is an optional and could potentially be nil. Before using an optional value, you need to unwrap it like so:

Alternately, we can use optional binding:

2. Control Flow

Anyone who’s programmed in C or a C-like language is familiar with the use of curly braces ({}) to delimit code blocks. In Swift, however, they’re not just a good idea: they’re the law!

This will raise a compiler error in Swift!

Unlike Objective-C, Swift treats curly braces as mandatory for if, for, while, and repeat statements. This might not sound like an improvement over Objective-C per se, but consider that even Apple’s own developers have had trouble without curly braces to keep them in line:

That’s right: the infamous iOS “goto fail” error could have been avoided if Objective-C was as strict as Swift about enforcing curly braces!

3. Type Inference

Swift introduces type safety to iOS development. Once a variable is declared with a particular type, its type is static and cannot be changed. The compiler is also smart enough to figure out (or infer) what type your variables should be based on the values you assign them:

This also means the compiler will raise an error if you try to assign a numeric value, such as 10, to our str2 variable:

Compare Objective-C, where you must always state a variable’s type explicitly:

4. Tuples

Swift supports tuples, values which store groups of other values. Unlike arrays, the values in a tuple don’t have to all be the same type. For example, you can have a tuple of Strings and Ints:

The most obvious use for tuples is returning multiple values from a function:

In Objective-C, we can use blocks in similar fashion, but it’s not as straightforward or elegant.

5. String Manipulation

Swift offers huge improvements over Objective-C in terms of string manipulation. For starters, you don’t have to worry about mutable vs. immutable strings anymore: just declare your string with var if you want to change it in the future, or with let if you need it to remain constant.

String concatenation is as easy as 1+1=2:

Compare Objective-C, where concatenating two immutable strings requires you to create an entirely new NSString object. Here’s an example using the “stringWithFormat” method:

As you can see here, string formatting in Objective-C involves inserting special placeholders for each different data type we want to interpolate into our string:

In Swift, we can instead interpolate values by inserting the variable names directly into our string:

6. Guard and Defer

Ever heard of the “pyramid of doom”? If not, here’s a snippet of Objective-C code that should jog your memory:

Now that’s a pyramid that would make even Indiana Jones blink! Fortunately, in Swift, we have guard, a new conditional statement which can make this code much more readable. Guard stops program flow if a condition is not met:

Swift also gives us the defer keyword, which provides a safe and easy way to handle code which we want executed only when the program leaves the current scope:

As you can see, we need to write four separate calls to destData.dealloc(dataSize) to make sure our pointer gets deallocated even if guard makes the function exit in the event of an error. With defer, we have a hassle-free way to clean up both our pointer and our code:

7. Functional Programming Patterns

Swift incorporates a number of functional programming features, such as map and filter, which can be used on any collection which implements the CollectionType protocol:

Objective-C has no built-in support for functional programming. To use these same kinds of functions, you would have to use a third-party library.

8. Enumerations

In Swift, enumerations are more powerful than they ever were in Objective-C: they can now contain methods and be passed by value. Here’s a little snippet of code which nicely illustrates how enums work in Swift:

Enums can also be recursive, so we can build a linked list using the indirect statement, which tells the compiler to add the necessary layer of indirection:

9. Functions

Swift’s function syntax is flexible enough to define anything from a simple C-style function to a complex Objective-C-style method with local and external parameter names.

Every function in Swift has a type, which consists of the function’s parameter types and return type. This means you can assign functions to variables or pass them as parameters to other functions:

Swift also allows you to define default values for function parameters:

10. Do Statement

The do statement in Swift allows you to introduce a new scope:

Do statements can also contain one or more catch clauses:

For more info, please refer to the official Swift documentation for the do statement.

Conclusion

We firmly believe Swift is the future of iOS development, and with its open source nature and growing popularity, we can expect to see it used on other platforms in the future.

One of its most promising features is what Apple calls Protocol-Oriented Programming, a paradigm which may have a huge impact on software development in the future. In Swift, protocols (or “Interfaces” in languages such as C#) can be implemented by not only classes, but also enums and structs as well; furthermore, they provide an elegant and confusion-free alternative to multiple inheritance, as a single object can implement multiple protocols.

With its light, flexible syntax and numerous features to guard against common coding errors, Swift is simply a joy to program with. Give it a try yourself – you’re almost certain to agree. A good place to start is Apple’s official (and quite thorough) documentation for the language.

About Redwerk

For almost ten years, Redwerk has developed solutions for e-government, broadcasting, business processes, and workflow automation. In our years in business, we’ve polished our workflow to cover the entire software development process from A to Z, ensuring our customers always get consistent, timely, and high-quality results. Redwerk has representatives in Ukraine, Germany, and the USA.

Our developers are also experts in

10 Differences Between Swift and Objective-C 4.20/5 (84.00%) 5 votes
  • David

    swift is for beginners and ObjC is for experienced developers, C,C++ is much better then swift!

  • Redwerk

    Thanks for your feedback! We are always happy to be at hand to our visitors and provide them with informative and useful content. What would you like us to write about in our next article?

  • narasimhaios nallamsetty

    Thanks for the wonderful tutorial. I have realized power of swift language now itself.