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!

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

Ken Mueller
Ken Mueller
iOS Development Techdegree Student 8,160 Points

Why unwrap non-optionals using if-let?

For some reason Pasan is using if let statements to unwrap the age and name in the friendDictionary, and I have no idea why because they are not optionals. He did not define that they should be optionals, but he did say that address is an optional but I do not see him unwrapping that.

2 Answers

David Papandrew
David Papandrew
8,386 Points

When you retrieve a dictionary value using subscript notation (via a key), the dictionary will return an optional. This is because it's possible there's no associated value in the dictionary for the key. This is why the if-let was used.

Might be confusing since I don't remember if he mentions this aspect of dictionaries in the video or not.

You can try it out in Playgrounds to see for yourself. In the example below "someAnimal" will be an optional:

let animals = ["cat": "meow", "dog": "woof", "cow": "moo"]

let someAnimal = animals["cat"]; print(someAnimal)

After going through whole lesson of "Downsides to Using If Let" I understand at last is The main Downside of using If Let is " here are lots of nested checks and we are back to the pyramid style again" If this is the main downside what is the point to show the two example before I don't quite get that.

In the first example he says " if we get a value for name and age, but don't get a value for address, then we still can return a valid instance of friend because we really don't need this This is optional.

The main thing I don't understand here is if we can return the instance of friend here, what is the downside here.

Please make me understand what is the downside in first two example.