Optionals in Swift “?”

What is optional type?

Optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”.

Why we need to use optional?

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.

When use optional?

when we have variable that can be nil or has no value at all anytime.

here, i try to use variable that has no value

but what if we user optional

We can use optional in many cases. It’s one of them.

How to declare Optional?

variableName : dataType?

ex: var myOptional : String?

Here’s the most important thing to know: An optional is a kind of container. An optional String is a container which might contain a String. An optional Int is a container which might contain an Int.

to use optional we need to unwrap it.

Unwrap optional

We have 5 Ways to unwrap optional

1- force unwrapping.

2- check for nil value.

3- optional binding.

4- nil coalescing operator.

5- optional chaining.

1- Force unwrapping “!”

It’s a simple way to use. but, you need to make sure that your optional value not nil when you use it. if it nil your app will crash.

All you need use “!” after optional variable.

force unwrap nil value:

2- Check for nil value

Here we will check if value is nil or not to avoid any errors.

we are not sure if value nil or not. so, it better to check it.

3- Optional Binding

Similar to above way but, here you don’t need to unwrap variable every time you use it.

4- nil coalescing operator

We use this way if we want to assign default value if our optional value is nil.

optional ?? default

5- Optional chaining “?”

Use with optional class or struct.

Adding “?” to struct avoiding any errors that equal to say get struct/class property or method if struct/class initialized.

Mobile Application Developer