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.
Zachary 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.