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 trialJUNSEI TEI
2,055 PointsGuard Statements in Initializer
CODE CHALLENGE... HELP ME
struct Book {
let title: String
let author: String
let price: String?
let pubDate: String?
init?(dict: [String: String]) {
guard self.title = dict["title"], self.author = dict["author"]
else{ return nil }
self.price = dict["price"]
self.pubDate = dict["pubDate"]
}
}
1 Answer
Martin Wildfeuer
Courses Plus Student 11,071 PointsYou can't really init a class member variable with the guard statement, so the easiest way would be using "helper variables".
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"]
}
}
Hope that helps :)
JUNSEI TEI
2,055 PointsJUNSEI TEI
2,055 PointsTHANK YOU!!!
Martin Wildfeuer
Courses Plus Student 11,071 PointsMartin Wildfeuer
Courses Plus Student 11,071 PointsYou are welcome! I see that you got an answer to the same question in another thread. It says that you don't have to use guard at all. True, there are more ways to address this. However, I do find the guard statement very easy to read, so I'd prefer the way you coded this.
r5
2,416 Pointsr5
2,416 PointsHey, Is it possible with this code to assign the struct Book to a constant an assign your values to title, author etc.? And if so what is the right syntax?
Thanks!