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?

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.