Logo

Swift Development Services – Apple’s Journey from Objective-C to Swift

Jan 05,2015
img

Back in 2008, Apple announced and released iPhone SDK 2.0. With this event sparked yet another revolution in software development, giving birth to a new breed of developers, called the iOS developers.

Many developers among them never used Objective-C prior to that and it was the first challenge Apple blew out to them. Despite the unfamiliar syntax and manual memory management, it was successful enough to populate the App Store with ten thousand apps. Apple kept on improving Objective-C and with each release, kept on adding block and literals, simplified memory management with automatic reference counting, and many other features pinpointing a modern programming language.

swift-objective-c-comparasion

In 2010, when iPhone was just 3 years old, the ability to code native apps was still nascent and iPhone came up with version 4 of the iPhone OS that included tantalizing new features like multitasking, fast app switching, and background services. Apple came back with a bombshell in iPhone OS 4 SDK and it was not in the software but in the usage agreement. It stated –

Applications must be originally written in Objective-C, C and C++, and only code written in C, C++, and Objective-C may compile and directly link against the Documented APIs.” – Section 3.3.1 of the iPhone OS 4 SDK Developer Agreement.

This new restriction took developers by surprise, but we heard Steve Jobs claiming it as a step to prevent the usage of cross-platform tools. However, Objective-C contributed largely towards the growth of the app ecosystem, but many developers started feeling dissatisfied in 2010 as a result alternative ways to write iPhone apps in other programming languages were cropping up.

After working with Objective-C for past 6 years, Apple decided to throw away yet another challenge this year in 2014 at WWDC. Yes, once again the iOS developers will need to learn an entirely new language called the Swift.

Swift – The New Apple Language

Learn-Swift-Programming-Language

Four years after 2010, Apple introduced developers to its new language, Swift. And this proved that Apple was ready to accept the truth that Objective-C might not be the best language for writing mobile apps. Swift is more a modern language compared to Objective-C. If new to Swift then you would have keen interest to know how to move from Objective-C to Swift.

You would notice two important differences between Swift and Objective-C –

Swift is not a strict superset of the C language – This denotes that Swift is free to make use of syntax constructs that was not in use. This helps to implement custom operators in Swift.

Swift is not dynamically typed, but typed statically – Statically typed means you can take the advantage of pioneered languages such as Haskell.

The Swift Launch Pad

In order to start exploring Swift you need to download XCode 6 from App Store and start experimenting. You can go to the home page of Apple’s Swift to find the best reference to facilitate Swift Development Services. To create a playground for your Swift Development here is a guide –
Variables and Constants
Declaring a variable in Swift profusely uses the VAR keyword.

var y = 1
var z = “Hello”

We choose two variable “y” and “z”. Swift is a safe language, it will deduce variable types from the assigned values. If you wish to make codes more readable, you can annotate the variable’s type.

var y: Int
y = 2

Constants are more or less similar, but you declare them using LET instead of VAR. The value of a constant does not need to be known at a compile time, but you must assign the value once.

let c1 = 1 // Constant known at compile time
var v = arc4random()
let c2 = v // Constant known only at run time

As their number suggest they are immutable so following the code is surely going to cause a compile-time error.

let c = 1
c = 3 // error

You can also declare other types as constant. As in this example, you can find that the following code an array declared as constant and if you try to modify it, the Swift compiler would fire an error:

Other types can also be declared as constant. For example, the following code declares an array as a constant, and if you attempt to modify any of the elements, the Swift compiler will report an error:

var arr2 = [4, 5, 6]
arr2[0] = 8
print (arr2) // [8, 5, 6]
let arr = [1, 2, 3]
a[0] = 5 // error

Optionals

You need to initialize constants when you declare them and for variables, you need to initialize them before you use. You cannot find it in Objective-C, but in Swift since optional values can have a value or be nil, but Objective-C cannot be nil equivalent. Look at the following code you will notice that that “x” assigned an optional value of 2015 at the same time this means Swift compiler was aware that “x” might be nil.

var s = “2015”
var x = s.toInt()
print(x) // Optional(2015)

If you introduce changes in this code and assign value “xyz” to “s” which cannot convert to integer, you will notice that “x” becomes NIL.

var s = “abc”
var x = s.toInt()
print(x) // nil

The return type of “toInt()” function is “Int?” which serves as the optional “Int”. Let us now consider a standard function on “x”:

var x = “2015”.toInt()
print(x.successor()) // error

Now the compiler sends signals as error, since “x” is optional and potentially NIL, we have to test “x” first and make sure that the successor function invokes a real number and not a NIL value.

var x = “2014”.toInt()
if x != nil
{
Print(x!.successor()) // 2015
}

We have to unwrap “x” by appending it with an exclamation mark (!). When we get sure that “x” contains a value we can easily access it, otherwise we can get runtime error. We also perform that function which Swift calls as optional binding, converting optional into a non-optional variable.

let x = “123”.toInt()
if let y = x
{
print(y)
}

The code will run if the “x” has a value to execute and will assign it to “y”. We do not need to unwrap “y” for that, as it is not optional as “x” is not NIL.Look at the Apple manual to read more details about Optional Chaining.

String Interpolation
When you use Objective-C, you usually do it with “stringWithFormat:” method

NSString *user = @”Gabriel”;
int days = 3;
NSString *s = [NSString stringWithFormat:@”posted by %@ (%d days ago)”, user, days];

Swift has a feature called string interpolation to do the same function, but it is easier to do and refined.

let user = “Gabriel”
let days = 3let s = “posted by \(user) \(days) ago”

You can also use expressions such as:

let width = 2
let height = 3
let s = “Area for square with sides \(width) and \(height) is \(width*height)”

Read more on string interpolation at Apple.

Functions
From Objective-C, the definition of function is different in Swift. Here is a sample function:

func someFunction(s:String, i: Int) -> Bool
{
… // code}

In Swift, the functions are of first-class types. This indicates that you can assign functions to variables, pass them as parameters to other functions, and make them returns types:

func stringLength(s:String) -> Int
{
return countElements(s)
}
func stringValue(s:String) -> Int
{
if let x = s.toInt()
{
return x
}
return 0
}
func doSomething(f:String -> Int, s:String) -> Int
{
return f(s).successor()
}
let f1 = stringLength
let f2 = stringValue
doSomething(f1, “123”) // 4
doSomething(f2, “123”) // 124

Again, in Swift you will find types of f1 and f2, although it is not possible to define them explicitly.
Functions can also return other functions:

let f1:String -> Int = stringLength
func compareGreaterThan(a: Int, b: Int) -> Bool
{
return a > b
}
func compareLessThan(a: Int, b: Int) -> Bool
{
return a < b
}
func comparator(greaterThan:Bool) -> (Int, Int) -> Bool
{
if greaterThan
{
return compareGreaterThan
}
else
{
return compareLessThan
}
}
let f = comparator(true)
println(f(5, 9))

Get to know more about functions at Apple’s Library.

Enumerations
Enumerations in Swift are powerful compared to Objective-C. Swift easily forms a structure, they can have methods to lie down and passes value:

enum MobileDevice : String
{
case iPhone = “iPhone”, Android = “Android”, WP8 = “Windows Phone8”, BB = “BlackBerry”
func name() -> String
{
return self.toRaw()
}
}
let m = MobileDevice.Android
print(m.name()) // “Android”

Compared to Objective-C, the enumerations in Swift can assign Strings, characters or floats as values for each member apart from the integers. You can find the convenient “toRaw()” method that returns the value assigned to each member. Enumerations also include parameters –

enum Location
{
case Address(street:String, city:String)
case LatLon(lat:Float, lon:Float)
func description() -> String
{
switch self
{
case let .Address(street, city):
return street + “, ” + city
case let .LatLon(lat, lon):
return “(\(lat), \(lon))”
}
}
}
let loc1 = Location.Address(street: “20, Connaught Place”, city: “New Delhi”)
let loc2 = Location.LatLon(lat: 28.6328, lon: 77.2197)
print(loc1.description()) // “20, Connaught Place, New Delhi ”
print(loc2.description()) // “(28.6328, 77.2197)”

Get information about enumerations here.

Tuples
Tuples are a group of several values turns into a single compound value. You can find that the value within the Tuples can be of any type and do not have to be of same type as each other.

let person = (“Thomas”, “Hardy”)print(person.0) // Thomas

You can also name the individual elements in Tuple:

let person = (first: ” Thomas “, last: ” Hardy”)print(person.first)

Tuples are extremely convenient options as their return types for functions that return more than one value.

func intDivision(a: Int, b: Int) -> (quotient: Int, remainder: Int)
{
return (a/b, a%b)
}
print(intDivision(11, 3)) // (3, 2)
let result = intDivision(15, 4)
print(result.remainder) // 3

Swift supports a pattern matching a switch statement, which you cannot find in Objective-C.

let complex = (2.0, 1.1) // real and imaginary partsswitch complex
{
case (0, 0):
println(“Number is zero”)
case (_, 0):
println(“Number is real”)
default:
println(“Number is imaginary”)
}

In the second example, we do not look into the number, so we use _ to match. You can also check additional conditions in each case as well. For that instance, we need to bind the pattern value to constants:

let complex = (2.0, 1.1)
switch complex
{
case (0, 0):
println(“Number is zero”)
case (let a, 0) where a > 0:
println(“Number is real and positive”)
case (let a, 0) where a < 0:
println(“Number is real and negative”)
case (0, let b) where b != 0:
println(“Number has only imaginary part”)
case let (a, b):
println(“Number is imaginary with distance \(a*a + b*b)”)
}

To know more on Tuples browse the Apple Library.

Classes
Swift does not require creating separate interfaces and implementing files for customized class or structures. In Swift, you can easily define a class or a structure within a single file and the external interface to that class or structure is made available automatically for other code to use.

Class definitions are very simple in Swift:

class Bottle
{
var volume: Int = 600func description() -> String
{
return “This bottle has \(volume) ml”
}
}
let b = Bottle()
pri
nt(b.description())

As you can see, declaration and implementation are in the same file. Swift no longer uses header and implementation files. Let us add a label to our example:

class Bottle
{
var volume: Int = 600
var label:String
func description() -> String
{
return “This bottle of \(label) has \(volume) ml”
}
}

The compiler will report the label is a non-optional variable and will not hold any value when a Bottle initialize.

class Bottle
{
var volume: Int = 600
var label:String
init(label:String)
{
self.label = label}
func description() -> String
{
return “This bottle of \(label) has \(volume) ml”
}
}

Well, we can also use optional type for a property we do not need to initialize that. In the following example, we made volume as the optional integer.

class Bottle{
var volume: Int?
var label:String
init(label:String)
{
self.label = label
}
func description() -> String
{
if self.volume != nil
{
return “This bottle of \(label) has \(volume!) ml”
}
else
{
return “A bootle of \(label)”
}
}
}

Structures
Swift also has structures just like Objective-C but it more flexible. Look at this example to get to know what structure defines in Swift:

struct Seat
{
var row: Int
var letter:String
init (row: Int, letter:String)
{
self.row = row
self.letter = letter
}
func description() -> String
{
return “\(row)-\(letter)”
}
}

Structures

Swift has structures that have methods, properties and intializers and some protocols as well. The difference between classes and structures is that classes pass on reference but structures pass by value.

let b = Bottle()
print(b.description()) // “b” bottle has 1000 ml
var b2 = b
b.volume = 750
print(b2.description()) // “b” and “b2” bottles have 750 ml

If we try out the similar case for instance with the structures, you will notice that it will pass by values:

var s1 = Seat(row: 14, letter:”A”)
var s2 = s1
s1.letter = “B”
print(s1.description()) // 14-B
print(s2.description()) // 14-A

Now, a question arises when we should use class or structure. In Objective-C and C, we used structures when we need to group multiple values and copy them rather than reference For example, complex numbers, 2D or 3D points, etc. However, class is traditionally the object. In Swift, we have seen that class and structure compared closely to other languages and much functionality can apply to either of the class or structure. As a result, general term used in Swift reference is “instance” which doth applies in any of these two.

You can read about Classes and Structures of swift at Apple Library.

Finding the Compatibility of Objective-C and Swift

    • A. iOS shares a common background with OS X and both hang on with the NeXTSTEP OS released in 1989. The later written in Objective-C and many of the core libraries trace their roots in these original implementations. Swift does not have its roots their but in future it will have to interface Objective-C.
    • B. Swift has enabled painless interactions with Objective-C, but that does not denote the process to be painless. Apple has given access to a helpful guide that explains how to call Objective-C code from Swift and vice versa. You will also come across some important impedance mismatch and must stay aware of them.
    • C. The most obvious mismatch that you might find here relates to the header files. Objective-C that has its root in C still needs their functioned to declare rather calling them. When you can out to a library, you would find the declarations found in the library’s header files. As for Swift, they do not use header files. If you want to call Swift Code from Objective-C, you need to create bridging header. Conceptually this may not seem complex, but it can be a tough task.
    • D. Another set of complication between Swift and Objective-C lies in their type systems. Swift that takes a various concept from other modern languages done away with the concept of NIL. In its place come Swift’s optional types. As for example, a method used to open a file only if it already exists would have a return type of a “File?” in Swift. By tacking all those places where types are optional, Swift compiler can effectively make it possible to encounter dreaded “Null Pointer Error”. Objective-C makes no guarantee about not returning nil. Rather Swift comes with special category of types called Implicitly Unwrapped Optional often used to call Objective-C code. These types treated as optional in Swift, along with overhead required for existence checking. You can use it alternately and can use the same as non-optional type, but if Objective-C does return, a “nil” will end up with a runtime error. Therefore, there are chances some of Swift’s compile-time safety guarantees.
    • E. Another subtle mismatch between Swift and Objective-C has to do away with how objects and classes created under the covers in the two programming languages from Apple. Objective-C due to their dynamic nature utilizes the dynamic dispatch to call methods on objects (via “objc_msgSend”). Swift definitely uses dynamic dispatch, but since it is statically typed it also get the option of using a “vtable” to store function pointers for each calling method. The two mechanisms that Swift uses depend on a number of factors Plane Old Swift Objects will use the “vtable” mechanism, unless the class or methods within the class annotates using the “@objc” Swift attribute.
    • F. Swift classes that have a chance to inherit from Objective-C classes will use dynamic dispatch for inherited methods. However, it is not possible for any new methods introduced by the subclass (well, you can force the use of dynamic dispatch with the “@objc” attribute). It is needless to say Swift code will be able to work with Swift classes, but Objective-C code can only utilize Swift objects and methods if annotated.

Swift is evolving daily at Apple’s Lab. You would come across a number of new things to learn about Swift. These include Generics, interaction with Objective-C libraries, closures, optional chaining, and operator overloading. It is not possible to discuss all of them in one article to describe thoroughly a new language.

Well, this quick read will help many developers get to know Objective-C, especially for those who have not yet managed time to learn details of Swift language can get on track.

Let’s talk about your project

Upload File (.doc, docx, pdf)