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

If-Let Swift

Can someone please explain "if-let" statements for me? Like what does it mean?

1 Answer

Hello Ryan. The if let statement is so that you can unwrap optionals in a safe way.

“You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that a value is missing. ”

Apple Inc. “The Swift Programming Language (Swift 2 Prerelease).” iBooks. https://itun.es/us/k5SW7.l

For example

var optionalString: String? = "Hello"

print(optionalString == nil) // this is “false"

var optionalName: String? = "Alejandro" // Notice how there is a value 
var greeting = "Hello!"

if let name = optionalName {
    greeting = "Hello \(name)"
}
// This will print “Hello Alejandro”

But if we don’t have a value, in the optionalName, and we don’t use the if let the system will crash.