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

what happens if i don't use ELSE to unwrap an optional and the value returned is nil?

If let statement allows us to unwrap optionals. What happens if we don not use the else statement in conjunction and the value returned was actually nil?

I am thinking that the code will just not execute. However the app will not crash as is the case if optional was not used at all.

1 Answer

// test is optional and nil
var test: String?

if let unwrappedTest = test {
   // You can only use unwrappedTest in this context
   // and only if test != nil
   // All code that does require a non-nil test belongs here
}

// test is still optional here, nil in this case 
// unwrapped test is not defined here

You don't necessarily need else if you simply don't want to execute any code if test is nil.

As a sidenote, Swift 2 introduces the guard statement, which is most probably what you are up to.

hey thanks so much for the answer and for elaborating on it. That was exactly what i wanted to know.