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?

Antonio Montalvo
Antonio Montalvo
10,549 Points

Problem executing the code provided at Swift Functions and Optionals

Swift 2.0

func findApt (aptNumber : String) -> String ?{ let aptNumbers = ["101","202","303","404"] for tempAptNumber in aptNumbers { if ( tempAptNumber == aptNumber) { return aptNumber } } return nil } if let culprit = findApt("505"){ print("Apt Found") }

This code won't run. I'm puzzled. Help please.

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

I did a couple things:

  • I took out the space between "String" and "?" when you defined your return value

  • I made a new variable of type String? and declared it first thing inside the code block. It's default value is nil. If it finds a matching aptNumber, it puts that String in, otherwise it stays nil. Regardless, it will return that variable.

Here's my code:

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


if let culprit = findApt("505") {
    print("Apt Found")
}