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 Swift Functions and Optionals Optionals What is an Optional?

Why 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
Francisco Navarro
14,185 Points

Hi 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

Hi,

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

'If let' unwraps the value because the '!' is implied in this statement.