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

Richard Sun
Richard Sun
11,257 Points

Error says variables title and author are optional strings, but they aren't

I don't understand how the user can get more than one key out a dictionary. Please help!

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

    init? (dict: [String: String]) {      
      self.title = dict["title"]
      self.author = dict["author"]

      guard let price = dict["price"], let pubDate = dict["pubDate"] else {
        return nil
      } 

      self.price = price
      self.pubDate = pubDate
    }
}

1 Answer

Ben Shockley
Ben Shockley
6,094 Points

They are optionals, because it's referring to the "title" and "author" being retrieved from the dictionary. A dictionary always returns and optional, so you have to unwrap it to get to it.

This is what you want your initializer to look like.

struct Book {
    let title: String
    let author: String
    let price: String?
    let pubDate: String?

        init? (dict: [String: String]) {
          if dict.isEmpty {
            return nil 
          }
        self.title = dict["title"]!
        self.author = dict["author"]!
        self.price = dict["price"]
        self.pubDate = dict["pubDate"]

        }

}

First you want to check and make sure the dictionary isn't nil, so you check it with the isEmpty function. If it is nil, then you return nil. If it isn't empty, then you So you use the bang operator ! to unwrap the value from the dictionary and set the constant to that value. You don't need to unwrap price and pubDate because they are being assigned to an optional constant, so it doesn't matter if they are nil or not. Does this make sense?