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
Initializing 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?
Anjali Pasupathy28,883 Points
We'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!