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?

boris said
boris said
3,607 Points

Kinda stuck getting this weird error

func findApt (aptNumber : String) -> String {
    let aptNumbers = ["101","202","303","404"]
    for tempAptNumber in aptNumbers {
        if ( tempAptNumber == aptNumber) {
            return aptNumber
        }
    }

    return""
}

if findApt("101") {
//apt found
}

1 Answer

I can see where that's not working quite right ...

You have created a method that takes a string and returns a string. That string contains a matching apt number if there is a matching one, or a blank string if there is not.

That's all fine - works perfectly. But you've not handled its operation properly below.

As above, this method returns something - it is a string. You've nested it inside an if statement which is expecting a boolean result. What you want to do is assign the result to something, like this:

// findApt method works fine here

var result = findApt("101")

That way, you are handling the returned value rather than leaving it floating out there doing nothing!

I hope that makes sense.

Steve.