swift · note · optionals
Optional Chaining Without Losing Intent
Context
Optional chaining is convenient, but it can make code too quiet if you use it everywhere. Sometimes the safer choice is the clearer one, even if it is a few lines longer.
The snippet
let city = profile?.address?.city ?? "Unknown"
label.text = city
Why this works
The expression handles the common nil path without extra branching. That is great when the fallback is simple and the intent stays obvious.
Use it when:
- the nil case has an obvious fallback
- you want to keep the code compact
- the optional path is genuinely optional
Avoid it when:
- the nil case matters and deserves its own branch
- swallowing the nil would hide a bug
- the code becomes hard to debug once chained
Takeaway: Optional chaining is best when it preserves meaning, not when it hides it.