Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Functions and Optionals Optionals Exercise: isDivisible function

Josh Ko
Josh Ko
1,510 Points

Clarity on "If - let" in unwrapping an optional

  1. Aside from wanting to store the result, why do we use "let result =" to unwrap an optional? It just seems to be a very cumbersome way to do things.

  2. If "let result = isDivisible(dividend: 11,divisor: 2)" and "isDivisible(dividend: 11,divisor: 2)" both equal nil why do I get an error when I try to use the latter in the if statement.

1 Answer

Max Hirsh
Max Hirsh
16,761 Points

If I understand it correctly, the isDivisible() function you use returns true or false depending on whether the dividend is divisible by the divisor? In that case, you would have an error because the if let method unwraps and stores an optional as a variable. You wouldn't be able to store the result to a boolean. That would sort of be like saying "the value of True is 7" or something. If you were trying to compare the optional logically after unwrapping it, I would recommend storing it as a variable first, then doing a comparison.