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 Review: Functions

Raymond Espinoza
Raymond Espinoza
1,989 Points

isDivisible

Cant seem to get the code right to let me know whether a dividend is not divisible by the divisor ?

2 Answers

Justin Reed
seal-mask
.a{fill-rule:evenodd;}techdegree
Justin Reed
Full Stack JavaScript Techdegree Student 33,458 Points

Hello Raymond,

This one had me stumped to until I reviewed Swifts comparison operators Equal to (a == b) Not equal to (a != b) Greater than (a > b) Less than (a < b) Greater than or equal to (a >= b) Less than or equal to (a <= b)

so its the exact same code as "isDivisible" except you change the comparison operator from "==" to "!=" and change the function name to "isNotDivisible" and your all set.

func isNotDivisible(#dividend: Int, #divisor: Int) -> Bool { if dividend % divisor != 0 { return true } else { return false } }

Hope this helps and if it does I would love to get best answer for the thread. Just finished the coursework and getting pretty close with my three apps but having a hard time getting points in the forum.

Good luck and happy learning

Justin

Leo Picado
Leo Picado
9,182 Points

Expanding on Justin's answer, you can reduce the amount of lines in your function, given that the evaluation of dividend % divisor != 0 will return a boolean value, into a single line, something like this:

func isNotDivisible(dividend:Int, divisor:Int) -> Bool {
    return dividend % divisor != 0
}

isNotDivisible(4, divisor: 2) // false
isNotDivisible(5, divisor: 2) // true

You can also see this problem this way, first find out if the remainder is zero, the negate that answer, so, something like this:

func isNotDivisible(dividend:Int, divisor:Int) -> Bool {
    return !isDivisible(dividend, divisor: divisor)
}

func isDivisible(dividend:Int, divisor:Int) -> Bool {
    return dividend % divisor == 0
}

Will yield the same result