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?

Optionals

Don't know what I'm doing bad here:

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
}

let result = ["Doc", "Grumpy", "Happy", "Sleepy", "Bashful", "Sneezy", "Dopey"]
if name = search("Doc") {
println("Found")

}

2 Answers

Chris Shaw
Chris Shaw
26,650 Points

Hi Basilio,

There is a couple of issues with your code, let's going through them.

  1. You have a named paramater aka #name, whenever you have named parameters you have to refer to them in your method call
  2. You have reassigned the array from the search method to result and haven't used a proper if-let statement

Fixing Problem 1

As I said whenever you have named parameters you need to refer to them, in the case of the search method it's asking for the following.

search(name: "Doc")

Fixing Problem 2

First off you don't need to reassign the array to an result constant, instead you want to use an if-let statement which checks for the optional and executes code inside the if statement if the result isn't nil.

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

By the end you should have the following.

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") {
  println("Found")
}

Happy coding =)

Yes, I try a little more before searching this answer and I complete it. Thanks anyway for the answer.

jonathan hegranes
jonathan hegranes
2,868 Points

Thanks for the answer. Curious though...

What are the benefits of using a named function?