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

Ryan Maneo
Ryan Maneo
4,342 Points

How do I unwrap title and author?

I am a bit confused on this part... I thought I did everything right... what am I missing? It says I need to force unwrap title and author but I've already sworn to never to do so... so how does one fix this? Am I supposed to be using guard let? (I tried it but it still didn't work)

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



    init? (dict: [String: String]) {
        self.title = dict["title"] // How do I
        self.author = dict["author"] // Fix this part?
        self.price = dict["price"]
        self.pubDate = dict["pubDate"]

    }

}

1 Answer

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Ryan,

You need to create a failable initializer. That means it should fail in some cases and return nil.

The reason we need to be able to do this is that dictionaries' keys are not guaranteed to be correct, and indexing into them returns optionals. The best way to do this is to use a guard statement. If we can't get the author or title from the dictionary, we'll return nil and not bother with the rest of the init method.

    init? (dict: [String: String]) {

        guard let correctTitle = dict["title"], let correctAuthor = dict["author"] else {
            return nil
        }

        self.title = correctTitle // If we make it down here
        self.author = correctAuthor // These are no longer optionals
        self.price = dict["price"]
        self.pubDate = dict["pubDate"]
    }

I hope that makes sense!

Cheers :beers:

-Greg

Ryan Maneo
Ryan Maneo
4,342 Points

It does, but it disappoints me that I was never told that guards can go inside of init statements... :/ I feel like so much is omitted in this Track. I like it sometimes because it pushes me to research it, but its frustrating at times.

Greg Kaleka
Greg Kaleka
39,021 Points

An init method is just a function like any other. You can use any logic statement inside init methods. Switch statements, for loops, if let, guard etc.

Keep working at it - it'll all start to mesh more soon :)