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 trial

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?