Swift – Optionals

Introduction

With the introduction to a new programming language known as SWIFT in the past year by the biggest technical giants Apple Inc, most dominant player in the mobile market, a new stage was set for developers to come up with more. I will agree that Swift is an easier platform to learn for all the developers though specially who are new to iOS development platform but shifting from Obj-C is not easy particularly not using the (*) pointer notation [Just kidding..].

Even if you are new to iOS there are lot of concepts that are not so friendly to understand and pretty much creates a confusion while learning and using the language basics.

One of most limbo concept is Optionals. It took me really good time to understand what it is all about specially when I was coming from the Obj-C background.

As it is said, there are 2 sides of the coin. Here to its has pros as well as cons. On the cons, the highly relative term is complexity. Trust me if you do not understand why ? or ! operators are used you will land in dead zone.

Let’s start with the basics.

With the new features in SWIFT every variable is required to be initialized. But as we know that is not true in very situation, we have situations where the items are to be assigned and calculated at runtime. To safe guard the application, SWIFT provide 2 operators that helps us in different scenarios.

? operator: Optional

You can consider this operator as a maybe operator. This operator is used in the place where we have a doubt that it might have the value or it might not have a value. It tells the compiler that the item marked with ? may also have a nil value.

var stringValue:AnyObject? = "Hello World";
println(stringValue);
println(stringValue!); //Force Unwrapping
stringValue! = "Hello Sir";

//Assign the value to non-optional
var actualStringNonOptional:AnyObject = stringValue!;
if let actualString: String = stringValue as? String
{
println(actualString);
}
var stringValueNil:AnyObject?;
var actualStringNonOptional2:AnyObject = stringValueNil!; // error

 

The first 4 lines of the above block shows the use of optional in the code.

** Remember that in case there is a nil while force unwrapping the variable, application will throw an exception and crash. So be sure if you are force unwrapping any variable make sure there is no condition it goes nil.

If you test the code in playground, you will see on line 2 output that is with Optional Keyword. This is how the compiler represents an Optional.

In the next code module, you can observe that for assigning the value to a non optional we either need to tell the compiler that “YES we know it has value by using !(force unwrapping).” The complier will trust the user and run the application without any checks.

The last line leads to the application crash as we try to unwrap an Optional which has a nil value.

! operator: Implicit UnWrapped Optional

The items marked with ! (exclamation mark) does not require forced unwrapping which means that compiler is intimated that user is confident that the variable has a value. The best example we can take is of IBOUTLETS which are marked implicit unwrapped optional. As specified in the previous section, it means the check is done at runtime and if the value doesnot exist then the application crashes.

var stringValue:AnyObject!;
println(stringValue);

As we can see that we do not need any Force Unwrapping here as the object is implicitly unwrapped.

I hope you enjoyed the post. Please share.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s