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

What is the solution of this?

I am not sure about the solution. Please let me know if anyone has done this.

Code Challenge:

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]) {
      return nil
     }

}

2 Answers

Dave Harker
PLUS
Dave Harker
Pro Student 15,510 Points

Hi ,

You've got it started there, just need to work through all objectives.
So let's guard those required variables and deal with failed initialization to meet the requirement:

Your task is to create a failable initializer that accepts a dictionary of type [String : String] as input

With something like this:

guard let title = dict["title"], let author = dict["author"] else {
    return nil
}

Now that's done we just need to finish up so we can

initializes all the stored properties.

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

Now you just need to put it all together. Keep going!

Dave.

Thank you Dave!