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 trialZachary Goforth
748 PointsHow do I modify the 'search' function to return an optional instead of just a String in Challenge Task 1?
I just learned optionals and obviously they want me to use one. After looking back at the code from the video these are my two guesses...
1)let names = search(name: "Snow White") names! 2) if let names = search(name: "Snow White") { println("Snow White") }
The reason I'm using "Snow White" is because when I put the code above in it tells me that since "Snow White" can't be found it should print nil... somehow. Optionals and nil make sense, but for me it's translating that into this task is where I'm lost.
func search(#name: String) -> String {
let names = ["Doc","Grumpy","Happy","Sleepy","Bashful","Sneezy","Dopey"]
for n in names {
if n == name {
return n
}
}
return ""
}
1 Answer
Juan Carlos Delgado Vidal
4,762 PointsHi, my best guess would be this:
func search(#name: String) -> String? {
let names = ["Doc","Grumpy","Happy","Sleepy","Bashful","Sneezy","Dopey"]
for n in names {
if n == name {
return n
}
}
return nil
}
so basically you set the return parameter to optional by adding the ? suffix. Then modify the return to nil if no name is found
Zachary Goforth
748 PointsZachary Goforth
748 PointsThese challenges are always easier than I think. I'll give it a try.