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

Ritesh R
PLUS
Ritesh R
Courses Plus Student 17,865 Points

True or Nil?

When the function isDivisible returns the value true or nil to the constant named "result" how is it comparing & printing? I mean shouldn't there be a comparison like if true print "Divisible" else "Not Divisible"??

3 Answers

Pasan Premaratne
STAFF
Pasan Premaratne
Treehouse Teacher

Ritesh R,

When you call the function using optional binding as shown below, it assigns the boolean result to the constant divisible.

if let divisible = isDivisible(number1: 16, number2: 4) {
    print("Divisible")
} else {
    print("Not Divisible")
}

If divisible is true, then control flow falls into the first statement and prints "Divisible". If it's false, it falls into the else block and prints "Not Divisible".

So implicitly this is what you're doing

if divisible == true {
    print("Divisable")
} else {
    print("Not Divisable")
}

Well put!

This is what I got:

func isDivisable(number1 number1: Int, number2: Int) -> Bool? {
    if (number1 % number2 == 0) {
        return true
    } else {
        return nil
    }
}

if let divisable = isDivisable(number1: 16, number2: 4) {
    print("Divisable")
} else {
    print("Not Divisable")
}
Ritesh R
Ritesh R
Courses Plus Student 17,865 Points

Yes i got the same but my question is how is it printing "Divisible"? we have not declared anything like if "true" then print "Divisible".

Emmanuel Darmon
Emmanuel Darmon
6,115 Points

I was asking the same question and all the answer is on the fist line: -> Bool?

if let statement means: If the function returns a Bool (True or False) it will print "Divisible" AND if the function returns a ? (something else, like nil) it will return "Not Divisable".

In your exemple, 16%4==0 so it will return a Bool (True here, but could be False) so it will print "Divisible" but if it returns something else (like the other option is nil here), it will return "else" = "Not Divisible"

Someone can confirm what I understood?