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?

Sujoy Singh
Sujoy Singh
10,620 Points

'=' used instead of '==' in an if statement.

How does the following if statement evaluate to a boolean expression?

if let culprit = findApt("102") {
    println("Apt found: \(culprit)")

The if statement here uses an assignment operator instead of a comparing operator.

Here the optional binding (Swift feature) is used. What it means is basically that if after using the function "findApt(#param)" you get a value, and this value is not 'nil', then perform the code to print this value (inside {}). You can think of it as a two step process: first, a value returned from "findApt(#param)" is assigned to culprit constant, and then this constant is compared to 'nil'.

1 Answer

Nathan Tallack
Nathan Tallack
22,159 Points

The = operator is an assignment operator. So in your example you are saying if I am returned any value other than nil from the function findApt passing in the string "102" as a paramater, then get that returned value, assign it to the constant let within the scope of the following code block. If it was nil then it would skip your code block.

So your println statement inside that codeblock gets the value of culprit from that if let (that's called an optional binding) and uses it in your string interpolation.

If you were to use the == operator, which is the equality operator, you would be creating invalid syntax. The optional binding (the if let) needs an assignment statement to follow it. You could not follow it with an equality statement.

An example of using the equality operator would be what your optional binding (the if let) is doing under the hood. Imagine you were not using optional binding and wanted to check that functions return value yourself. Then you could write it out like this.

if findApt("102") == nil {
    println("Apt not found!")
} else {
    println("Apt found!")

I hope this helps. :)