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 trialTarcan Arca
3,572 PointsWhat's wrong with this initializer?
I would like to add a failable initializer in an existing struct called "Book". I don't get what's wrong with my initializer. Can anybody help?
Code is as follows:
struct Book {
let title: String
let author: String
let price: String?
let pubDate: String?
func initialize(dict: [String: String]) -> Book? {
guard let title = dict["title"], author = dict["author"] else {
return nil
}
let price = dict["price"]
let pubDate = dict["pubDate"]
return Book(title: title, author: author, price: price, pubDate: pubDate)
}
}
2 Answers
Greg Kaleka
39,021 PointsHi Tarcan,
I'm on mobile, so I can't check all your code, but I'm afraid you haven't written a failable initializer at all - you've written a function called initialize. An initializer must be called init, and a failable initializer should just be init?. No need for the func keyword.
Let us know if that works!
Cheers
Greg
Tarcan Arca
3,572 PointsThanks for the help, it worked!