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

JUNSEI TEI
JUNSEI TEI
2,055 Points

Guard Statements in Initializer

CODE CHALLENGE... HELP ME

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

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

    }

}

1 Answer

Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points

You can't really init a class member variable with the guard statement, so the easiest way would be using "helper variables".

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

Hope that helps :)

Martin Wildfeuer
Martin Wildfeuer
Courses Plus Student 11,071 Points

You are welcome! I see that you got an answer to the same question in another thread. It says that you don't have to use guard at all. True, there are more ways to address this. However, I do find the guard statement very easy to read, so I'd prefer the way you coded this.

r5
r5
2,416 Points

Hey, Is it possible with this code to assign the struct Book to a constant an assign your values to title, author etc.? And if so what is the right syntax?

Thanks!