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.

iOS Swift Functions and Optionals Optionals What is an Optional?

Optional Challenge 1 of 2

Hey all, I'm kinda stuck on this question. This questions asked to modify the codes into an optional and to return a nil if the name is not found in the array.

Here are my codes :

func search (name: String) -> String? {
    let names = ["Doc","Grumpy","Happy","Sleepy","Bashful","Sneezy","Dopey"]
    for n in names {
        if (n == name) {
            return name
        }
    }
    return nil
}

I've ran the codes on XCode and it was fine. Im not sure what's wrong.

search.swift
func search (name: String) -> String? {
    let names = ["Doc","Grumpy","Happy","Sleepy","Bashful","Sneezy","Dopey"]
    for n in names {
        if (n == name) {
            return name
        }
    }
    return nil
}

3 Answers

Chris Shaw
Chris Shaw
26,650 Points

Hi Nick,

It appears you've accidentally altered the argument name which should be named aka it should have a pound # in-front of it.

func search(#name: String) -> String?

Happy coding!

Vittorio Somaschini
Vittorio Somaschini
33,371 Points

Hello Nick!

I think the problem is in where you have written your "return nil" code, as you should not touch the default return "" line, while you dealt correctly with the optional.

I give you this hint:

We have a situation where we want to return the name IF it exist, if it does not exist (ELSE) we want to return nil.

Thanks guys! Appreciate your help :)