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 trialDavid Lin
Full Stack JavaScript Techdegree Student 8,116 PointsCould 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
14,575 PointsWell, 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.
Alex Benyon
2,517 Points3 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)")
}