Optionals and Unwrapping optionals in swift
(map/flatmap/optional chaining/optional binding/ Optional casting and optional error handling)
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
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 placeholderWrapped
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
- Forced Unwrapping
- Optional Binding
- Optional chaining
- With implicitly unwrapped optionals, using
!
- Nil coalescing operator
- 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.
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: