What is Optional in Swift?

What is Optional? and Why Optional?

When declaring variables in Swift, they are designated as non-optional by default. In other words, we have to assign a non-nil value to the variable. Otherwise, the compiler will show the error.
If we are declaring the variable as Optional (?) we can pass the nil value to the variable.
If we want to access the optional variable we have use either ? or !.

Swift is Code Safe programming language. So, Optional is product from the nil value passing.

?.
Whenever we are trying to access the Optional variable we have to use “?.”. This means we can even get “nil” values.

!.
If we damn sure that the optional variable should have non-nil values then we can use “!” to access the variable.
But, this is not safe. Because, in case of passing nil value to the variable at runtime the app will be crashed.

Eg 1:
Let consider we have one customer class which has protocol methods and we declared the protocol object. And we are conforming the protocol obj by passing the value “self” to the obj. Now the below code will work fine without any issues,

Custom Class and View Controller.
1. Protocol interface:

protocol demoCustomProtocolDelegate {
func cancelTheView ()
func didSelectThePickerItemInView (slectedItem : String)
}

2. Declaring with Optional (?):

var itemPickerViewDelegate : pickerViewProtocolDelegate?

3. In ViewController we are passing value to the protocol object:

customViewObj.demoCustomProtocolDelegate = self

4. Fire the protocol methods by conforming protocol obj:
4.1: We are directly performing the protocol method. It will work fine even, it the protocol obj has nil value. Because, the optional variable will take care of nil values. Even “!.” will also work fine because, the object has value. By using “!” we are unwrappping our selfs.

self.itemPickerViewDelegate?.cancelTheView() (OR)
self.itemPickerViewDelegate!.cancelTheView()

4.2: Here we are unwrapping the optional and checking whether the obj has non-nil value or nil value. If it is non-nil we are performing the action.

if let _ = self.itemPickerViewDelegate
{
self.itemPickerViewDelegate?.cancelThePickerview() (OR)
self.itemPickerViewDelegate!.cancelThePickerview()
}

Now, consider the scenario like if we pass the value as nil to the protocol obj from ViewController

5.     customViewObj.demoCustomProtocolDelegate = nil
6.     self.itemPickerViewDelegate?.cancelTheView().

This will work fine without any issues because, compiler will try to unwrap the optional values and if will realize the value is nil and it will not perform the action.

7.    self.itemPickerViewDelegate!.cancelTheView()

This will crash at run time. Because, we are unwrapping our self from the optional variable but, it has nil value. So, the code will be crash.

Eg: 2

1. var optionalSample :  String?
2. optionalSample = “Value”
print(“Optional Sample: \(optionalSample)”)
O/P: Optionala Sample: Optional(“Value”)
3. By using “!”
optionalSample = “Value”
print(“Optional Sample: \(optionalSample!)”)
Optional Sample: Value
4. By passing nil
optionalSample = nil
print(“Optional Sample: \(optionalSample!)”)
Now, it will be crashed and the Error message is:
fatal error: unexpectedly found nil while unwrapping an Optional value

Hope it will give you some idea on Swift Optional. Please let me know your feedback on this.

Warm Regards,
Yuvaraj Manickam.