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?

George Hamilton
George Hamilton
2,777 Points

Is this correct? The if let syntax creates the culprit constant and assigns it the return value only if the value != nil

So the "if let" syntax creates the culprit constant and assigns it the return value only if the value != nil; otherwise the culprit constant is not created at all.

1 Answer

Stone Preston
Stone Preston
42,016 Points

yep thats right. this is known as optional binding since you bind the value of the optional to a constant or variable. you can add an else clause to handle the case when the optional is nil if you wanted.

if let someConstant = someOptional {

    //optional has a value
    println(someConstant)

} else {

   //optional is nil

}

you can bind the optional value to a variable as well, although most of the time a constant is fine

if var someVariable = someOptional {

    //optional has a value
     println(someVariable)
} else {

   //optional is nil

}