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

Why does assigning the return value of the function to a constant created in the if condition solve the error message?

So given a correctly written isDivisible function, if we do:

<pre><code> if isDivisible(num1, num2) { \\ do something } else { \\ do other thing } </code></pre>

xCode gives an error that the optional type bool? cannot be used as a boolean. If we then instead do:

let result = isDivisible(num1, num2)

if result { \\ do something } else { \\ do other thing }

xCode gives the same error as above, saying that optional type bool? can't be used as a boolean. But how come the following code works without erroring?

if let result = isDivisible(num1, num2) { \\ do something } else { \\ do other thing }

Why does assigning the return value of the isDivisible function to a constant declare in the if condition pass the error check when the other two types don't?

1 Answer

the function isDivisible returns an optional isDivisible(num1, num2) -> Bool?, so if you want to get it's value you have to unwrap it (using the !).

let result = isDivisible(num1, num2) is an optional of type Bool? and not a Bool, to use it's value you need to unwrap it first.

// result is an optional of type Bool?
let result = isDivisible(num1, num2) 

// result! is the value of the optional might be of type Bool or nil
if result! {
  // Do something
} else {
  // Do something else
}

the if let it's an optional binding that makes it easier to test if an optional has a value.

if let result = isDivisible(num1, num2) {
  // Do Something
} else {
  // Do something else
}

In this conditional, the existence of a value returned by the function is tested first. If the returned value is nil, the else statement is executed. If is not nil, the optional returned by the function is unwrapped and assigned to the constant result.