Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Endi Hıdır
Endi Hıdır
1,762 Points

I couldn't understand what this question asked me. Can someone give me a clue or an answer. The code I wrote is below

In the editor, you have a struct named Book which has few stored properties, two of which are optional.

Your task is to create a failable initializer that accepts a dictionary of type [String : String] as input and initializes all the stored properties. (Hint: A failable init method is one that can return nil and is written as init?).

Use the following keys to retrieve values from the dictionary: "title", "author", "price", "pubDate"

Note: Give your initializer argument the name dict

optionals.swift
struct Book {
    let title: String
    let author: String
    let price: String?
    let pubDate: String?

    init?(dict: [String: String], title: String, author: String, price: String, pubDate: String) {
        self.title = title
        self.author = author
        self.price = price
        self.pubDate = pubDate
        if let title = dict["title"], let author = dict["author"]{
            let price = dict["price"]
            let pubDate = dict["pubDate"]
            Book(dict: ["My": "Books"], title: title, author: author, price: price!, pubDate: pubDate!)
        }

            return nil

    }

}
Endi Hıdır
Endi Hıdır
1,762 Points

Thank you so much Amazon Web

1 Answer

Alright! You don't need to add all the properties in the argument of init method, you only need the dictionary.

init? (dict: [String: String] {
     //The code below belongs here
}

Next you need to get the value of title and author from the dictionary. If these values are nil you need to return nil (because these properties are non optional)

if let title = dict["title"], let author = dict["author"] {
     self.title = title
     self.author = author
}else {
     return nil
}

Finally, you need to get the value of price and pubdate from the dictionary. If these values are nil, no problem! Because these are optionals (so they can have nil values),

self.price = dict["price"]
self.pubDate = dict["pubDate"]