What if your code could skip missing pieces without breaking, like magic?
Why Optional chaining with ?. in Swift? - Purpose & Use Cases
Imagine you have a phone book, but some people don't have a phone number listed. You want to call a friend, but you have to check if their number exists first. Doing this for many friends by hand is tiring and confusing.
Manually checking if each phone number exists before calling is slow and easy to forget. If you try to call without checking, your program might crash or give errors. This makes your code messy and hard to read.
Optional chaining with ?. lets you safely ask for a property or call a method on something that might be missing. If the thing is missing, it just skips the call and returns nil instead of crashing. This keeps your code clean and safe.
if let friend = person.friend { if let phone = friend.phoneNumber { print(phone) } }
print(person.friend?.phoneNumber ?? "No phone number")
It makes your code safer and easier to write when dealing with things that might be missing or nil.
When building an app, you might want to show a user's profile picture only if it exists. Optional chaining lets you try to get the picture without crashing if the user hasn't set one yet.
Optional chaining helps safely access properties or methods on optional values.
It prevents crashes by returning nil if something is missing.
It makes code shorter, cleaner, and easier to understand.