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?

Erik Trinidad
Erik Trinidad
3,696 Points

Why isn't this working? Optionals Challenge Task 2 of 2

Why isn't this working?

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

1 Answer

Michael Hulet
Michael Hulet
47,912 Points

Adding the octothorpe in your function declaration makes it necessary to write the name of the name variable in any calls to the function. See if this works:

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
}
//Notice how you must write the name of the variable called name in the call to search below
if let result = search(name: "Doc") {
  println("Found: \(result)")
}

Alternatively, you could remove the octothorpe in the definition of the search function, and the rest of your original code would work, like this:

//Notice the lack of a # in the below line
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("Doc") {
  println("Found: \(result)")
}