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 trialHaeJu Lee
3,811 PointsQuestion 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
14,575 PointsHello 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
1,649 PointsHi 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!