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

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?