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 return Bool in exercise?

I don't see why you wouldn't get the function to complete the task fully. Is this code incorrect?

func isDivisible(#number1: Int, #number2: Int) -> String {
    if number1 % number2 == 0 {
        return "Divisible"
    } else {
        return "Not Divisible"
    }
}

Thanks Matthias but I am not sure I understand you. Comparing my example of code with one I have just amended to reflect the "answer" given by Amit:

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

if let result = isDivisible(number1: 2, number2: 2) {
    println("Divisible")
} else {
    println("Not Divisible")
}

I find that this "correct" version is verbose and I can't see a difference in functionality. Is there a reason my original code couldn't be used in another scenario?

Well it's not really verbose, printing the result is only for testing, you don't really want a String, you want to know whether two numbers are divisible and that's a true or false question. It shouldn't be an optional either since number1 and number2 aren't optionals either. You also need have to check whether number 2 is zero or not, or you'll divide by zero

Thanks Matthias,

I was being dense - it's been a long day!

1 Answer

As Matthias Schlemm pointed out it's much easier to build a conditional around a function that returns a boolean than it is to evaluate a string return.

  if( isDivisible(number1: 1, number2: 0) ) {
    // do something
  }

  if( isDivisible(number1: 1, number2: 0) == "divisible" ) {
    // do something
  }

On top of producing easier to read code it's also more efficient. Booleans take up very little space in memory and comparing a boolean is a more efficient operation than comparing two strings. In general if your function asks a true/false question it should return a boolean.

Great! Thanks Geoff. Completely makes sense that it would be easier to use later and that it saves power to compute in more complex situations. Can't believe I didn't notice that earlier really!