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 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