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 Enumerations and Optionals in Swift Introduction to Optionals Initializing Optional Values

Joan Perez Lozano
PLUS
Joan Perez Lozano
Courses Plus Student 3,190 Points

what's missing here (Failable init)

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]){
      guard let titl = dict["title"], let auth = dict["author"] else {
        return nil
      }
      return Book(title: dict["title"], author: dict["author"], price: dict["price"], pubDate: dict["pubDate"])
    }
}
Kevin Pape
Kevin Pape
Courses Plus Student 3,892 Points

This is what you are supposed to do. You want to assign the values. I know, it can sometimes be a bit confusing.

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"]
    }
}