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 trialdipanchokshi
3,216 PointsWhat is the solution of this?
I am not sure about the solution. Please let me know if anyone has done this.
Code Challenge:
In the editor, you have a struct named Book which has few stored properties, two of which are optional.
Your task is to create a failable initializer that accepts a dictionary of type [String : String] as input and initializes all the stored properties. (Hint: A failable init method is one that can return nil and is written as init?).
Use the following keys to retrieve values from the dictionary: "title", "author", "price", "pubDate"
Note: Give your initializer argument the name dict
struct Book {
let title: String
let author: String
let price: String?
let pubDate: String?
init?(dict: [String: String]) {
return nil
}
}
2 Answers
Dave Harker
Courses Plus Student 15,510 PointsHi ,
You've got it started there, just need to work through all objectives.
So let's guard those required variables and deal with failed initialization to meet the requirement:
Your task is to create a failable initializer that accepts a dictionary of type [String : String] as input
With something like this:
guard let title = dict["title"], let author = dict["author"] else {
return nil
}
Now that's done we just need to finish up so we can
initializes all the stored properties.
self.title = title
self.author = author
self.price = dict["price"]
self.pubDate = dict["pubDate"]
Now you just need to put it all together. Keep going!
Dave.
dipanchokshi
3,216 PointsThank you Dave!