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 trialPranav Mahajan
2,272 PointsThe question is not very clear to me
The init? is suppose to return nil. Then why do we need the keys of the dictionary?
struct Book { let title: String let author: String let price: String? let pubDate: String?
init?(dict : [String : String]){
if let title = dict["title"], let author = dict["author"]{
return nil}
// title = dict[""]
// author = dict["author"]
//price = dict["price"]
//pubDate = dict["pubDate"]
}
}
struct Book {
let title: String
let author: String
let price: String?
let pubDate: String?
init?(dict : [String : String]){
if let title = dict["title"], let author = dict["author"]{
return nil}
// title = dict[""]
// author = dict["author"]
//price = dict["price"]
//pubDate = dict["pubDate"]
}
}
1 Answer
Daniel Santos
34,969 PointsPranav,
This is what worked for me, analyze it and let me know if you don't understand my solution:
init? (dict: [String: String]) {
if let title = dict["title"], let author = dict["author"] {
self.title = title
self.author = author
} else {
return nil
}
self.price = dict["price"]
sefl.pubDate = dict["pubDate"]
}
-Dan
Pranav Mahajan
2,272 PointsPranav Mahajan
2,272 PointsThanks. I understood the logic by reading your code.
I thought that ?init can only return nil. Yes it can(which is the error scenario), but we have to handle the happy scenario as well. I thought ?init isn't meant for writing code for happy scenario & I was wrong.
Daniel Santos
34,969 PointsDaniel Santos
34,969 PointsGreat that you understand!