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 trial

iOS Swift 2.0 Enumerations and Optionals Introduction to Optionals Initializing Optional Values

Tarcan Arca
Tarcan Arca
3,572 Points

What'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
Greg Kaleka
39,021 Points

Hi 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 :beers:


Tarcan Arca
Tarcan Arca
3,572 Points

Thanks for the help, it worked!