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

David Lin
seal-mask
.a{fill-rule:evenodd;}techdegree
David Lin
Full Stack JavaScript Techdegree Student 8,116 Points

Could we utilize Optional along with Tuple?

I try to use all I have learned so far in this course to do this exercise; Just out of curiosity, could we combine Optional with Tuple when creating a function?? Is it the "right way" in term of coding. My code for this exercise is followed...

func divisbleNumber (#firstNum: Int, #secondNum: Int) -> (Bool, String)? { if firstNum % secondNum == 0 { return (true, "(firstNum) is divisble by (secondNum)"); }else { return nil; } }

if let result = divisbleNumber(firstNum: 10, secondNum: 5) { println("Divisible") } else { println("Not Divisible") }

2 Answers

Jhoan Arango
Jhoan Arango
14,575 Points

Well, it seems that the code you have does work. One thing I’ve learned is, if the problem you are trying to solve, is solved no matter how you write the code, then it’s good.

3 months after the question I know, but surely the answer to the David's question is No, this is not 'good' code as you have recreated the code that you went to all the trouble to eliminate. The way you have written the 'if let' statement it doesn't call the strings from the tuple in the function ( you can check this by changing them, the console output wont change)

(Also you missed the backslashes to interpolate the strings in the function - although that might be a result of pasting into the question box without formatting into a code block)

To achieve what you are aiming to, the code should look like this:

func divisbleNumber (#firstNum: Int, #secondNum: Int) -> (Bool, String)? {
 if firstNum % secondNum == 0 { 
return (true, "\(firstNum) is divisble by \(secondNum)"); 
}else { return nil; }
 }

if let result = divisbleNumber(firstNum: 10, secondNum: 5){
 println("\(result)")
}