Optional in Swift— Learning the Why

Swift comes with a new concept of optional and non-optional variables. Before answering Why Optional?, you need to know what is Optional in swift?

var someOptionalString: String? // Optional 
var nonOptionString: String = “123” // Non-Optional

What that ? in the declaration means? Well, this is a way to declare optional variable in swift.
Ok. But what the heck is this Optional?

Optional is a way of representing either there is value in a variable or nothing i.e. absence of value.

From the above code, someOptionalString optional variable we can conclude that it can either contain some string value or nothing at all.

In swift, nil is a special value to represent the absence of value. So, someOptionalString may either contain string value or it may be nil.

Ok. So far clear. But why Optional?

Let me explain you with example:

-(NSString *)getFormattedPhone:(NSString *)phone{
if (phone.length == 10) {
NSString *countryCode = “+91”
return [NSString stringWithFormat:@”%@-%@”, countryCode, phone ]
}
return nil;
}
NSString *formattedPhone = [self getFormattedPhone:@”2233231341223"]; // nil is returned
NSString *message = [“Phone: “ stringByAppendingString:formattedPhone]; // runtime error
NSLog(@”%@”, message);

What if we write the same code in Swift:

func getFormattedPhone(phone: String) -> String? {
if (phone.length == 10) {
return "+91" + phone
}
return nil
}

var formattedPhone:String? = getFormattedPhone("2233231341223")
let message = "Phone: " + formattedPhone // compile-time error
println(message)

Because of type safe nature of Swift, compiler will warn us at compile time, as we are trying to add String and String?.To use an Optional variable value, we have to unwrap that optional variable.

Hey, wait.. Now what is unwrapping an Optional?

Unwrapping is a process to get the underlying value of an optional variable.

There are different ways of unwrapping, but for now we will discuss only two basic ways:

If statement and forced unwrapping:

var formattedPhone:String? = getFormattedPhone("2233231341223")
if formattedPhone != nil {
let message = "Phone: " + formattedPhone!
println(message)
}

First, we make sure that formattedPhone is not nil i.e. it contains some value and if that is true, then we use ! at the end of variable to force unwrap the value in the if block.
Using force unwrapping without prior check of nil, leads to runtime error.

Optional Binding:

var formattedPhone:String? = getFormattedPhone("2233231341223")
if let formattedPhoneTemp = formattedPhone {
let message = "Phone: " + formattedPhoneTemp
println(message)
}

Using this option for unwrapping Optional, if formattedPhone contains any value, then that value is assigned to temporary variable formattedPhoneTemp and this temporary variable is available in the if block to use.

So, use of Optional saved us from a critical bug that we are able to find now at the compile time, which we would not have been found using Objective-C code until a runtime error occurred. That would be crucial, if it came in production app.

If you like the post, hit the ❤️ button and spread the word.
Comment below to give your feedback and help me improve the content.