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

Kyler Smith
Kyler Smith
10,110 Points

Return a valid instance. Swift 2.0 optionals.

I understand that by using guard I am setting up a fail path that if any of the values inside it's scope result in nil, it will exit, but I don't really understand what I should be returning in my "init?" scope's "happy" path?

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

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

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

        self.title = dict["title"] // needs a bang (!) to compile
        self.author = dict["author"] // needs a bang (!) to compile
        self.price = dict["price"]
        self.pubDate = dict["pubDate"]
        return nil
    }
}

1 Answer

Cindy Lea
PLUS
Cindy Lea
Courses Plus Student 6,497 Points

You were almost there...self.title & self.author need modifying: struct Book { let title: String let author: String let price: String? let pubDate: String?

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

}

Kyler Smith
Kyler Smith
10,110 Points

Thanks! I made the changes suggested, but I still seem to be getting an error? (Make sure the initializer returns a valid instance given a valid dictionary).

edit: I do have a question though. Does the guard have it's own scope or am I able to use the variables that are created after the guard keyword outside of that scope, because it seems like you are assigning the self.title and self.author to the guard's scope variable?

Kyler Smith
Kyler Smith
10,110 Points

Got it! I did not realize you removed the return statement at the bottom of the second condition in the init? method. Thank you!