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 trialAustin Whitelaw
9,065 PointsInitializing Optional Values Question
Okay so I just completed this code challenge after running through a bunch of troubles. I figured it out by glancing at some other code, and then realizing the way it should be setup.
In case you don't know this specific challenge, you have to create a failable initializer for a struct with two strings title and author, and two optional strings price and pubDate.
What I don't understand is, if the constants price and pubDate are optionals, then how come we are using a guard for title and author?
1 Answer
Anjali Pasupathy
28,883 PointsWe're using a guard statement for title and author because title and author are suppose to be Strings, not Optional Strings. We can't guarantee that dict will contain the key "title" or "author", so dict will return an Optional String when you use either key. Because of this, we need to optionally unwrap them with a guard statement. Inside the else clause of the guard statement, we return nil because if we're entering that clause, it means dict doesn't have the keys "title" or "author".
I hope this helps!
Austin Whitelaw
9,065 PointsAustin Whitelaw
9,065 PointsThanks I kinda understand it better now, I had forgotten that we get optional strings from a dictionary.
I guess I just don't understand why we don't have to use guard for price or pubDate, considering those two are created as optional strings.
When I first tried this challenge, I put all 4 of them into the guard.
Anjali Pasupathy
28,883 PointsAnjali Pasupathy
28,883 PointsWe don't use a guard statement for price or pubDate because those properties are Optional Strings. Because Optional Strings are returned from a dictionary, we can just set those return values to price and pubDate without having to worry about unwrapping them.
Austin Whitelaw
9,065 PointsAustin Whitelaw
9,065 PointsSo let me see if I am understand this correctly. Based upon what you are saying, it seems that if you specify an optional then you don't have to guard when you are using a dictionary. But if you don't specify an optional then you need a guard when using dictionary?
Anjali Pasupathy
28,883 PointsAnjali Pasupathy
28,883 PointsYep, that's about right! Dictionaries can return a nil value if the key isn't in the Dictionary, and only Optionals are allowed to be nil.