Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Enumerations and Optionals in Swift Objects and Optionals Optional Chaining

Why there can't be a question mark after buildingNumber?

We have this code:

let buildingNumber = susan.residence?.address?.buildingNumber

We put a question mark after every variable which can be nil. It works with residence and address, but why not with buildingNumber? The type of it is String? so buildingNumber can be nil as well

I have a theory why this happens. It seems adding a question mark after a variable works only if it is followed by something (e.g. "residence?" is followed by "address?").

And therefore, it seems that what question mark does for other variables, is done automatically for the last variable in the chain

Am I right?

1 Answer

Tyler Barnes
Tyler Barnes
6,688 Points

You are right that there is no question mark needed after buildingNumber, because it is the last property in the chain. The question marks in optional chaining prevent the system from trying to access a property of nil. Let's say you have a variable called someNumber, and you want to assign it to buildingNumber. You can do this:

let buildingNumber = someNumber

The above will always be valid, even if someNumber is nil. That would just make buildingNumber also nil. But now let's say you have an optional variable called address, and you want to access the buildingNumber property. This syntax would be problematic:

let buildingNumber = address.buildingNumber

The above will fail if address is nil, because nil has no property 'buildingNumber'.