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 trialAnthony Boyd
1,047 PointsI don't get how to solve this question on optionals
The search function below returns a name if it is found in the array and an empty string if it is not found. Modify the search function to return an optional instead of just a String. In addition, you have to make sure the function returns a nil if the name is not found in the array.
How do you do this task
3 Answers
Micahyah Hawkins
3,496 PointsHello Anthony
To make the return value optional you need to add a ? to the end of the return value:
func search(#name: String) -> String? {
Now once it is an optional you have the rest of the function as normal. With the for and if statements if it the name is found it will return the name. Though if it does not find the name it will drop out of the if and for statement and execute the ending return statement. In the example it currently returns "" but the question states to return nil. So you will change the "" to nil. Please see below.
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 to recap on the first line of the fund you add the ? to the return value String.
Then if it does not find a name you change the empty string "" to nil
I hope this helps
Laurentiu Szabo
1,870 Pointsfunc search(#name: String) -> String? {
let names = ["Doc","Grumpy","Happy","Sleepy","Bashful","Sneezy","Dopey"]
for n in names {
if (n == name){
return name
}
}
return nil
}
if let person = search(name: "Doc") {
println("\(person) was found")
}
Benjamin Jones
2,269 PointsMine is working in Xcode but not in the browser.. surprise surprise!!
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" }
search(name: "Snow White") - // added this in to test it in Xcode and returns "nil"