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?

What in the world does "unwrapping an optional" mean?

I've watched the "Swift Functions & Optionals" video twice, but I still don't understand this term.

1 Answer

Michael Hulet
Michael Hulet
47,912 Points

An optional is a variable that could either contain a value or nil. In order to find out which one it is, you need to "unwrap" it. This is done in one of 2 ways. You could either unwrap it implicitly (also known as "if let" syntax), like this:

//This variable could either contain a String or nil. In this case, it will contain the string "Hello"
var optional: String? = "Hello"
//Because it could be nil, we have to check if it is before we can use it
if let validString = optional{
    println(validString)
}

If you need to perform a quick operation and know the value won't be nil, you could explicitly unwrap it (using an exclamation point), like this:

//This is an optional, same as before
var optional: String? = "Hello"
//We're lazy and wanna save a couple lines, and we know it's not nil, so we can explicitly unwrap the optional variable
println(optional!)