Optionals and Unwrapping optionals in swift

(map/flatmap/optional chaining/optional binding/ Optional casting and optional error handling)

Manasa M P
4 min readJan 15, 2021

What is optional?

Swift introduces optional type, which handles the absence of a value. Optional says either “there is a value, and it equals x” or “there isn’t a value at all”.

How to create an Optional?

simple way to create optional in swift is to add ? in front of the type like below

optionalString has a value or there isn’t a value.

Optional is a super powered enum which has two values. None and Some(Wrapped), where Wrapped is an associated value of the correct data type. It looks like this

In fact, the Optional enum uses the generic type placeholder Wrapped so that any type can be made optional!

What are the ways to unwrap optionals?

If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. You need to follow any way to unwrap optionals

  1. Forced Unwrapping
  2. Optional Binding
  3. Optional chaining
  4. With implicitly unwrapped optionals, using !
  5. Nil coalescing operator
  6. Unwrapping using higher order function

Forced Unwrapping:- Unsafe.

It can be achieved by using ! at the end of the variable.

Optional Binding:- Safe

It can done using if let or guard let statement

Optional Chaining:- Safe

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil . A useful approach for working with optionals is optional chaining, especially if you’re dealing with multiple optionals at once.

Sample example for optional chaining.

With implicitly unwrapped optionals, using ! :- Unsafe

You can declare optional variables using ! instead of a question mark. Such optional variables will unwrap automatically.

Nil coalescing operator:- Safe

assign default value for the optionals using ?? . If optional has value, then you will get value assigned for optional else you will get default value

Unwrapping using higher order function:- Safe

Unwrapping functionality can be achieved through higher order functions map/flatmap

How Optional is used for Error Handling?

When function throws an error with swift, you have to handle those error with do-try-catch block.

What is Optional Casting?

When you type cast a value in swift, you’re checking the type of that value, and you can treat it as a different type within its own class hierarchy.

How can we use switch statement with optional?

Optional is an enum so you should be able to use the switch statement to deconstruct its cases. Like this:

I am happy to share this article with you. If you’ve enjoyed this article, do show support by giving a few claps 👏 . Thanks for your time and make sure to follow me or drop your comment below 👇

--

--

Manasa M P
Manasa M P

No responses yet