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 trialMathew Munro
1,652 PointsDo you need the 'else' comparator in a function with optionals?
My solution was pretty much the same as Amit's with one exception.
The function as I wrote it was:
func divisible (#numberOne : Int, #numberTwo : Int ) -> Bool? {
if numberOne % numberTwo == 0 {
return true
}
return nil
}
In Amit's example however he uses the 'else' part of 'if-else' to return that nil value.
func divisible (#numberOne : Int, #numberTwo : Int ) -> Bool? {
if numberOne % numberTwo == 0 {
return true
} else {
return nil
}
}
Both methods seem to work but out of interest is one of these ways considered to be the 'proper' approach to this?
2 Answers
Michael Hulet
47,913 PointsEither method works just fine. It's totally a matter of preference. I prefer Amit's, personally, because it sounds better when you read it aloud. Remember: the goal isn't to write a program in the least amount of lines possible, but to write a program in the best way possible (which usually means the most readable, easy to maintain way)
Srinivasan Senthil
2,266 PointsBoth will work fine. Just the If statement, is compared as the If-Then statement in C. If-Else is the If Then Else statement in C. If you have a action that gets completely satisfied in If class, then just finish it with If statement alone.
There is no need to put in IF Else statement. Again this is a big topic among the developers. Either way is fine.