Optional Chaining In Swift

Updated 25 March 2021


As we can understand by its name “Optional” that means It may or may not have some value. it is the process to call the methods and structure if it has some value it returns some value if not it return nil, it is Optional Chaining.

Optional Chaining as an Alternative to Forced Unwrapping

If you are using optional chaining then you need to specify it as in the below

you are using Forced Unwrapping then it must have some value else this code generate always error

Once you determine the type does contain optional values, you can add an optional name behind an exclamation point (!) To get the value. The exclamation point said, “I know that there are optional values, use it.” This is called mandatory optional parsed value (forced unwrapping).

if you want to use option chaining you need to use a question mark at the place exclamation mark like below

If the name not any value it will return nil but it doesn’t generate any error at the run time.

Accessing Properties Through Optional Chaining

You can access the properties of other classes, structures, etc by making their object. like below

Calling Methods

You can call a method like below

The whole point to get an unwrapped copy of the original object that you can use safely, even if your original object could be modified by other threads as well. So don’t discard the safely unwrapped value, use that value later on instead of doing optional chaining on the optional value.



I hope this blog helped, If you have any query please leave a comment to us and for more blogs please click here.

. . .

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