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

JT Keller
JT Keller
12,731 Points

isDivisible Function Exercise - Improvement

For the most part, my solution matched Amit's however, I think it's important to make an additional check within the function. The purpose of the function is to determine whether 2 integers are divisible by one another (defined by no remainder). It's also important to keep in mind that you can't divide by 0 as this isn't mathematically possible and also generates a divide by 0 error. Below is the function that used to first check to make sure the divisor wasn't 0 and then check to make sure that there's no remainder.

Happy Coding!

import UIKit

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

if let test = isDivisible(firstNumber: 10, secondNumber: 10) {
    println("Divisible")
} else {
    println("Not Divisible")
}

1 Answer

Indeed, I tried it this way:

func isDivisible (#divident: Int, #divisor: Int) ->Bool? {
    if divisor == 0 || divident % divisor != 0 {
        return nil
    } else {
        return true
    }
}
Karl Metum
Karl Metum
3,447 Points

You can improve this further by removing the else clause.

func isDivisible (divident: Int, divisor: Int) ->Bool? {
    if divisor == 0 || divident % divisor != 0 {
        return nil
    } 
    return true
}