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!

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?

Challenge Task of Optional Quiz

can anyone explain what is wrong with my code? and also explain about the optionals?

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

if let result = search(name: "DOC") {

1 Answer

Brendan Whiting
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,734 Points

when you called the "search" function at the bottom, you asked it to find "DOC" instead of "Doc", and it is case sensitive, so it didn't match, and didn't print out "Found".

Optionals are a data type that can contain something, or be nil - contain nothing. In this case, the "String?" type can be a string or it can be nil. In this case, there's a possibility that you could ask for a name, and there would be no match. You also need to check to see if there's a value inside an optional before "unwrapping" it, otherwise your program could crash.