Optional Chaining in Swift

Moussa Hellal
2 min readApr 24, 2023

Optional chaining capability in Swift allows developers to safely access the properties and methods of an optional variable without first having to unwrap it.

The symbol?’ indicates optional chaining and can be chained together to access nested properties and methods.

Here’s an example of how optional chaining can be used in Swift:

In this example, we have two structs, Person and Information, where Person has an optional Information property.

We create a Person instance with a non-nil Information property and use optional chaining to safely access the age property of the person’s information. We then change the person’s information to nil and use optional chaining again to try to access the age property, which now returns nil.

Optional chaining is helpful in situations where you have a chain of optional values and you need to safely access properties or methods along that chain without force-unwrapping any of the optionals.

Most importantly, It allows you to handle nil values gracefully and avoid runtime errors and unexpected crashes.

I appreciate you choosing to spend some of your day with me. I hope that my piece was informative and helpful to you.

Farewell, keep growing and learning and see you in the next one. ✌️

Make sure to follow me on Twitter to keep receiving the newest articles:

https://twitter.com/mosesCodeOs

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response