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

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,018 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?