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 Downsides to Using If Let

Welby Obeng
Welby Obeng
20,340 Points

Fast forward to 5:53, Why does name and age being a string optional matter?

To Pasan Premaratne and others

Fast forward to 5:53,

  1. Why does name and age variables being a string optional matter for the Friend Struct? We exit the function if it's nil so why does it matter ?

  2. Is the teacher saying by default every variable declared is optional? how did name and age variables become optional?

1 Answer

Pasan Premaratne
Pasan Premaratne
Treehouse Teacher
  1. Swift is a type safe language. An optional String is not the same type as a String. An optional string can be nil but a string cannot. Name and age being optionals matter here because you cannot use an optional string value where a string is expected.

  2. When you access a value from a dictionary using a key, the value returned is an optional (in this example dict is the dictionary). The reason it works this way is because there is no guarantee that a key may exist in a dictionary. If the key exists, it can return a value, otherwise it returns nil. This behavior, either being a value or nil, is what an optional is, and by design dictionaries return optional values. Does that make sense? That is why name and age here are optionals