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 trialPaul Je
4,435 PointsInitializers may only be declared within a type? How would I declare dict as a type?
Not sure how to declare it as a type, and is there anything else wrong with my code? Thought creating an array with the various properties of the Book struct would do it - I have a feeling the problem may lie in the initialization of each property to the init parameter arguments.. thanks!
struct Book {
let title: String
let author: String
let price: String?
let pubDate: String?
}
init?(dict: [title: String], [author: String], [price: String], [pubDate: String]) {
Book.title = title
Book.author = author
Book.price = price
Book.pubDate = pubDate
}
2 Answers
Steven Deutsch
21,046 PointsHey Paul Je,
This challenge is asking us to create a failable initializer for the Book struct. The initializer will take a dictionary as its parameter and use that dictionary to provide values to the stored properties of Book. Since it's possible that this dictionary will not have the data necessary to provide values to the Book instance's properties, it is a failable initializer.
We know that the dictionary's type is [String: String] because the challenge says that the keys are Strings and all the types of our properties, which we will be setting from the values, are Strings.
Since the first two properties, title and author, are not of the optional type, they must have a value. Therefore, I created a guard statement to make sure that values for the "title" and "author" keys are not nil. If they are, the initializer will fail and return nil.
The other two properties, price and pubDate are of the String? type. This means they can have a nil value. Therefore, if the value's for the "price" or "pubDate" keys are nil, or if those keys do not exist, then the nil value can be safely accepted by this property.
struct Book {
let title: String
let author: String
let price: String?
let pubDate: String?
init?(dict: [String: String]) {
guard let title = dict["title"], let author = dict["author"] else {
return nil
}
self.title = title
self.author = author
self.price = dict["price"]
self.pubDate = dict["pubDate"]
}
}
Good Luck!
Paul Je
4,435 PointsThanks Steven that cleared it up so much
Steven Deutsch
21,046 PointsNo problem. Had to fix the typos