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

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
}