Swift – Optional | Implicit Optional | Optional Binding | Optional Unwrapping

We will learn about Optionals?, their unwrapping, implicitly unwrapped optional!, optional binding and automatic unwrapping.

Normal Optionals :

What : Optionals (normal) are data types, which have value or nothing. ? mark is used to denote optional. Optional means , it may have or may not have any value. think optional(?) as as box (which can contain some thing or nothing) and ! exclamation mark as key of the box. To fetch value from optional var we need operator exclamation mark !

When : when you want to declare a variable, which may or may not have value in future. Suppose you get API response which “may” have person’s first name, middle name and last name. you can simply use optional data type(?) for all three variables.

Declaration : var nameOfYourVariable : Type?

Implicitly Unwrapped Optional :

What : “implicitly unwrapped” optional, meaning that you do not have to unwrap it to access the value.

When : To make sure it must not be nil, and you do not need to deal with unwrapping.

Declaration : var nameOfYourVariable : Type!

/**************example************************************/


/**************example************************************/


Optional Binding : 

What : To find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.

When : Most recommended way to unwrap optionals.

Syntax : 

if let someValue = someOptional{

//…………use this someValue variable

}else{

//……it means someOptional is nil, it has no value.

}

/**************example************************************/


/**************example************************************/


Implicitly Unwrapped Optional : 

What : Sometimes it is clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be safely assumed to have a value all of the time.

These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.

When : Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter.

/**************example************************************/