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

HaeJu Lee
HaeJu Lee
3,811 Points

Question about [Case of NOT USING "if let" syntax]

Amit used below.

if let result = isDivisible(dividend: 15, divisor: 3) { ... }

I tried to use the following,

if isDivisible(dividend:15, divisor:3) { ... }

which triggers this error message.

"optional type 'Bool?' cannot be used as a boolean; test for '!=nil' instead."

Well, I don't see the difference between

"if isDivisible(dividend:15, divisor:3)" and

"if let result = isDivisible(dividend: 15, divisor: 3)" ,

Because isDivisible(dividend:15, divisor:3) itself also returns true or nil.

Why should I introduce a new constant "result" to make my code run?

2 Answers

Jhoan Arango
Jhoan Arango
14,575 Points

Hello HaeJu Lee:

“You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that a value is missing. Write a question mark (?) after the type of a value to mark the value as optional.”

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2 Prerelease).” iBooks. https://itun.es/us/k5SW7.l

Andrew Wertheim
Andrew Wertheim
1,649 Points

Hi Jhoan (and HaeJu Lee, and Amit)

I had a similar question. I set my code up the same way as HaeJu Lee and noticed the same error. I modified my code to test for != nil instead and my code gives the same results as Amit's example. My code is below. My question is, is there a reason that I should use if let and create a new variable as Amit does just to unwrap the optional? Or is there danger in doing it my way, bypassing creating the new variable with if let..?

My code:

if divTest(numOne: 100, numTwo: 25) != nil { println("Divisible")

} else { println("Not Divisible") }

Thanks for the help guys. This has been a great course so far!