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 trialAlx Ki
Python Web Development Techdegree Graduate 14,822 Pointssimpler 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
42,016 Pointsno 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.