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 trialEd Williams
2,969 PointsWhy not return a tuple (Bool, String) instead of an optional String?
Is there a reason why this example returns an optional String instead of a Bool? From the previous lesson, I learned this could be done using a tuple. Why do we do this...
func findApt(aptNumber: String) -> String? {
let aptNumbers = ["101", "202", "303", "404"]
for tempAptNumber in aptNumbers {
if (tempAptNumber == aptNumber) {
return aptNumber
}
}
return nil
}
When we could do this...
func findApt(aptNumber: String) -> (hasCulprit: Bool, culprit: String) {
let aptNumbers = ["101", "202", "303", "404"]
for tempAptNumber in aptNumbers {
if (tempAptNumber == aptNumber) {
return (True, aptNumber)
}
}
return (false, "")
}
if (findApt("101").hasCulprit) {
// ...
}
Is there a reason to use an optional instead?
3 Answers
obey me
1,135 PointsFrom what i learned when you make a your function optional , it help to test any possible way without crashing because its not every time you will test a function and get a fix result . I hope this help .
Umut Kahramankaptan
1,349 PointsIf you can guarantee no apt number could be an empty string, ""; then you do not need to use a Tuple anyhow, since it will be mutually seperated. I guess that optional is used (specifically when I hear "optional chaining", and I haven't seen that video yet), in a concept very close to exceptions.
With "optional" approach functional signature will be much more clear. It returns a String, if it can. With "tuple" approach, you will always include it as a data.
But most probably under the hood, it is using a very similar mechanism.
Adam Short
11,153 PointsThe first option is more compact, easier to write and look at and, this is just a wild guess, could be used for Integers. I might be wrong, but I don't think you could achieve the same result with the same amount of code using tuples for both integers and strings.