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 trial

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)")
}