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

Alx Ki
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alx Ki
Python Web Development Techdegree Graduate 14,810 Points

simpler without else? or not?

Do we have any reason to use else in isDivisible function? Can my solution cause any problems?

func checkDivisibility(#first: Int, #second: Int) -> Bool? {
    if first % second == 0 {
        return true
    }
    return nil
}

if let Divisible = checkDivisibility(first: 15, second: 4){
    println("Yup! That's truly divisible!")
} else{
    println("No Way..")
}

1 Answer

Stone Preston
Stone Preston
42,016 Points

no you do not need to use else:

func checkDivisibility(#first: Int, #second: Int) -> Bool? {
    if first % second == 0 {
        return true
    }
    return nil
}

in the above code, if the condition in the if is true the function returns true and thus stops immediately, if its not true it returns nil. else is not necessary. whenever you use return inside a function it stops after that point and returns whatever value you said to.

however you could use else if you wanted to be more explicit:

func checkDivisibility(#first: Int, #second: Int) -> Bool? {
    if first % second == 0 {
        return true
    } else {
        return nil
    }
}

I actually kind of prefer using else since its more clear to the reader that it will return true if the condition is true, and return nil if not.