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

Juliano Jakymiu
Juliano Jakymiu
2,040 Points

Cant seem to get it right with this code

The error says that title and author are optionals Strings not unwrapped. I am guessing that the compiler is referring to the dictionary string being an optional but in any case I don't know how to unwrap it.

Ive tried guard, '!', '?', but that is not what the exercise wants.

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"]
    self.price = dict["price"]
    self.pubDate = dict["pubDate"]

    return nil

    }

}

2 Answers

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Juliano!

This is a tricky one. I strongly recommend you go back and watch the previous video because we can apply it directly to this challenge. Here are the things you need to know:

  1. Indexing into a dictionary (with something like dict["author"]) returns an optional.
  2. In our initializer, it's going to be OK to have those optional values for price and pubDate, but not author and title.
  3. You can use guard let to unwrap dictionary values, and if they fail, you can return nil from the initializer. Like so:
guard let author = dict["author"] else {
    return nil
}

That should get you started. Watch the video again, and then give it another try. Remember, to successfully create an instance, you need to set author and title to unwrapped values, but price and pubDate can (must) be optionals.

Good luck!

Cheers :beers:

-Greg

I have this problem, too. Is this how the whole code looks like?

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

    init? (dict: [String : String]) {
    guard let author = dict["author"] else { return nil }
    guard let title = dict["title"] else { return nil }
    guard let price != nil else { return price}
    guard let pubDate != nil else { return pubDate }

    }
}

Was I supposed to erase the

return nil

in the code, or was I supposed keep it?