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 Enumerations and Optionals in Swift Objects and Optionals Nil Coalescing Operator

Should firstName be a constant or variable?

I tried doing all three examples in this video: i.e. if let, ternary conditional operator and nil coalescing operator, if the situation was that the user of the app did not provide their name. i.e. let firstName: String?. I got an error each time. Shouldn't firstName be a variable in this case to give the user the option of providing a first name? (that's how it worked for me in the end).

1 Answer

Brian Cornelius
Brian Cornelius
2,227 Points

I know I'm a bit too late to answer your question, but for future viewers wondering the same thing:

Using a constant with no name will allow the code to execute as planned. The problem with your "let first name: String?" is that it's not being initialized. Constants must always be initialized, even if it's just set to nil. If you simply set the constant equal to nil, the code would run as planned. "let first name: String? = nil" The reason you were successful once it was changed to a variable is because they're not required to be initialized.