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 2.0 Enumerations and Optionals Introduction to Optionals Optional Binding

Wrapping/Unwrapping

In this video, Pasan talks about wrapping, unwrapping, and force unwrapping.

Could someone explain what these terms mean? I don't remember them being talked about in the Swift track yet.

Thank you in advance!

2 Answers

Daniel Cunningham
Daniel Cunningham
21,109 Points

Hello, The gist behind 'wrapping' and 'unwrapping' optional values begins with understanding that when you use an optional, you are creating some sort of constant, variable, or other value that could contain varying data types (ex. an optional "String?" value could either be a String or a Nil datatype). As a result, if you write functions that EXPECT a datatype like a string, but enter an optional value that contains a nil value, your code will fail unless you create a safeguard to expect a nil value. As a result, swift structured optionals such that the compiler will fail if you have not produced safeguards in your code to expect the possibility of a nil value. You could consider these language safeguards as a "wrapping" that you need to "unwrap" in order to use the value in a function. "Force unwrapping", which the Pasan says (many times) should be used as sparingly as possible, uses the exclamation point (!) to bypass the need to create those safeguards and allows the value to be used.

I would recommend finishing the course and then going back to the beginning to review this the first two videos in the sequence. It is about 13 minutes of hypothetical scenarios and does a pretty good job of abstractly speaking about the purpose and the risks of optional values. Pasan begins using the terms "wrap" and "unwrap" in the middle of the "Working with Optionals" video preceding the Optional Binding video.

https://teamtreehouse.com/library/swift-20-enumerations-and-optionals/introduction-to-optionals/working-with-optional-types

Hope that helps and best of luck!

Awesome answer, thank you for the help! I'll go back and rewatch those couple videos.

Thanks again, I appreciate it!