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

Do 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
Michael Hulet
47,843 Points

Either 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
Srinivasan Senthil
2,266 Points

Both 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.