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 2.0 Enumerations and Optionals Introduction to Optionals Working with Optional Types

Is unwrapping an optional not required in String Interpolation?

struct Person { let firstName: String let middleName: String? let lastName: String

func getFullName() -> String{
    return "\(firstName) \(middleName) \(lastName)" //no error
    return firstName + " " + middleName + " " lastName //error - Value of type 'String?' not    unwrapped


When I type this code out in Playground, I don't get any error that indicates that middleName has to be unwrapped, whereas if I don't use String Interpolation, I do get an error. Does this mean that unwrapping optionals is not required within String Interpolation?

2 Answers

Jason Anders
Jason Anders
Treehouse Moderator 145,858 Points

Hey Madelyn,

That's a really good question, and really not explained anywhere in the Swift Docs that I can find. If I remember correctly, it is talked about in one of the Swift videos here on Treehouse, but I really can't remember which one.

So, I will try my best to remember why... In Swift, optionals have to be unwrapped. The thing is they can be unwrapped automatically by the code. This is what is happening with String Interpolation. When the variable is interpolated, it is checked (unwrapped) by Swift. If the variable is empty it returns nil and "nil" will be printed to the string.

Concatenation, on the other hand, doesn't come with this 'auto-unwrap' feature, which is why you are getting the error.

I will try to remember the video this is addressed it, but I hope this clears it up a bit for you. :)

Keep Coding! :dizzy:

Thank you for your simple, clear explanation. It makes a lot of sense when explained!

Mostafa Mohsen
Mostafa Mohsen
6,688 Points

if the optimal has a value String Interpolation will print optional (value) and you have to ununwrap the value