Optional Binding in Swift

Updated 30 June 2022

Save

Throughout programming, we get into moments that variable will have no value assigned to it or it could contain a value. We call these variables Optionals in swift programming. Optional binding is a common practice of unwrapping nil values safely.

Let us discuss how the binding process works, by following steps.

Output: We are having coffee

Output: the optionals is nil

Crashing

Sometimes we force unwrap optionals by using an exclamation mark at the end of the variable. In this case, if the optionals have nil value, then it will force the program to crash.

For example:

Which gives EXC_BAD_INSTRUCTION

To avoid these types of crashes, we use optional binding. To unwrap optionals, we can use the exclamation mark “!” or double question mark with a value, the variable will use this value when the optional is nil.

For example:

Output: Hello World

Optional Unwrapping:

if -let statements :

Similarly, we can also use if let statements to unbind the optionals. We can use this to find out whether an optional contains a value. If so, make that value available as a temporary constant or variable.

For example:

Output: This is Swift

Guard Statement :

Guard statements are simple and powerful. It checks for some conditions and if it evaluates to be false, then the else statement will execute which will exit the method. This is another way of writing if let statement.

For example:

When 1 is executed, output:

Hello John!

Location of John is unknown.

When 2 is executed, output:

Hello Jane!

Jane lives in Cupertino

Conclusion

In this blog, we learned about OptionalBinding and safe methods to avoid crashes when unwrapping an optional variable. You can read more about OptionalBinding in swift from here.

You can read more of my blogs from this link.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home