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 trial

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,676 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 :)