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?

Jon Schenck
Jon Schenck
2,028 Points

Help with optionals

Need help with the second task of the swift optionals challenge. I am unable to get this to work and need assistance

search.swift
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 == names {
  println("Found")
}


search(name: "Doc")

2 Answers

Hi Jon,

Your mistake is with the if let usage.

You want to assign the returned value from the search function into result and output Found if the name is returned from the search method.

That could look like:

if let result = search(name: "Doc") {
  println("Found")
}

I hope that helps.

Steve.

Ali Kayhan
Ali Kayhan
3,331 Points

From what I see, you need to assign what is returned from search function to result so that if something returns from search function, the condition will be satisfied. In your code, you don't check if something returns from search function. Also, remember that when you are out of the function, names variable (or constant) is not something declared, so basically you can't check if result == names.