Optional in Swift

Swift Optional is the fundamental part of the Swift coding. Optional is used to separate the good code from the bad code and prevent crashes. Every programming language has some preventive measures to avoid a crash. Swift is more practical in this case and optional make your code crash free.

Declaration

Optional type is used whenever you use optional values, even if you never typed the word Optional. Swift's type system usually shows the wrapped type's name along with a question mark (?) instead of showing the full type name.

For example, if a variable has the type Int?, it is same and just another way of writing Optional. This short form is used just to keep code easy and simple.

See the following example.

Here, the types of shortForm and longForm in the following code sample are the same:

Optional either hold no value or some value. Optional allows storing nil as the absence of a value. Optional is a generic enum with two cases:

  • Optional.none: It is equivalent to nil literal.
  • Optional.some(Wrapped): It stores a wrapped value.

Example

Output:

true

The question mark (?) in the above program denotes that it is an optional variable. If you see a question mark at the end of a variable declaration, it is definitely an optional and it may or may not contain a value in it. So, at some part of your program, you don't know if there is a value or not for a variable, then mark it as optional.

Now, see this example:

Here we try to print the value of the variable 'numberOfStudents'.

Here, the exclamation point (!) at the end of the variable is used to unwrap the value. But, if will try to execute the code the code will crash. That is because, you just force unwrap an optional variable with no value in it. If there is no value in the variable, the program will be crashed.

Set a value to the variable

If you set a value to the variable before you force unwrap the value, the code will not crash but this is not a good coding practice and an abuse of optional variable.

Output:

30

You can do a nil check before you force unwrap an optional.

For example:

Now, your program will not crash as you are force unwrapping the optional variable only after a nil check.

The above method will check if the optional variable 'numberOfStudents' contains some value or not. If exists, then it will be copied to a constant called studentCount and then only the code block will get executed.

Forced Unwrapping

When you define a variable as optional then to fetch the value from this variable, you will have to unwrap it. Force unwrapping is the process of putting an exclamation mark at the end of the variable.

Let's check an example to make it clear.

Example: (Before applying unwrapping)

Output: When you execute the above code, it will give the following output:

Optional("Hello World")

Example: (After applying unwrapping)

Now, we apply unwrapping to get the correct value of the variable.

Output:

Hello World

Automatic Unwrapping

Automatic unwrapping provides a way where the optional variable is declared using exclamation mark instead of a question mark. By this way, variables will be unwrapped automatically and you do not need to use any further exclamation mark at the end of the variable to fetch the assigned value.

Let's see an example.

Example:

Output:

Hello World

Swift Optional Binding

Optional Binding is used to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. You can use any of the optional binding control structures, including if let, guard let, and etc.

Let's take an example to see the optional binding for the if statement:

Example:

Output:

The value of my string is - Hello world