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 trialspalak
12,151 PointsWhy does the if statement return a string?
Here it says:
if let culprit = findApt("404")
Why does the value become "404" instead of 'Some "404"', if you do not include the if statement?
Thanks
3 Answers
Francisco Navarro
14,185 PointsHi spalak,
I don't know if I understood what are you asking for. The purpose of using the if statement is to avoid a runtime error because of the "optional" String you are returning from findApt().
If you just code:
let culprit = findApt("404")
, you will get a struct with 'Some "404" ' and in order to use it you need to unwrapped doing "culprit!" but you could get an unexpected error if findApt() return nil.
The use of the "if let" statement avoid you to unwrap all the process above described and if you code:
if let culprit = findApt("404")
You'll get the value already unwrapped if findApt return not nil so culprit would be ready to use.
Hope that helps
spalak
12,151 PointsHi,
Why does the if statement unwrap the value? I don't follow why the statement doesn't return the same unwrapped value, given that absent the if statement, you need to add the bang.
Thanks, Syam
luckyluckyluke
2,683 Points'If let' unwraps the value because the '!' is implied in this statement.
Anthony Barcamp
1,791 Pointsthis article might be useful https://medium.com/arthurs-coding-tips/optionals-in-swift-c94fd231e7a4