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 Build a Weather App with Swift Simple Data Structures Bootstrapping the UI

O Or
O Or
2,761 Points

I'm confused Optional Chaining vs Unwrapping

2:20 in the video he talks about using optional chaining to unwrap the currentTemperatureLabel of type UILabel?

but in his code I only see optional chaining

currentTemperatureLabel?.text = "(currentWeather.temperature)"

so currentTemperatureLabel?.text is of type String? and I feel it is still unwrapped even though its usable by the label, currentTemperatureLabel, in optional form.

If I am missing something I would appreciate suggestions.

Thanks

2 Answers

Ryan Jin
Ryan Jin
15,337 Points

Using someVariable?.aProperty means that the variable, which might be nill, will be either unwrapped and gets its property, or do nothing since it is 0. So this will return an optional value since you are not sure wether or not this variable holds a value, so if it is not nill, it will get its property, and return an optional value. If the variable itself is nill, then you will simply get nill.

O Or
O Or
2,761 Points

that makes sense thanks

Stepan Ulyanin
Stepan Ulyanin
11,318 Points

Most likely currentTemperatureLabel is optional of type UILabel?. To use any methods on optional you need to unwrap the value, but sometimes it is more convenient to use optional chaining: currentTemperatureLabel?.text unwraps the label and gives you the access to its text property. If your label happen to return nil then currentTemperatureLabel?.text won't trigger an error in run time, apple calls it "failing graciously" or something like that haha