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

Waylan Sands
PLUS
Waylan Sands
Courses Plus Student 5,824 Points

Can someone please explain this code

This was the answer to a code challenge. We have gone over stucts, initializers, and optionals though I thought this was a little behond the scope of the lessons so far. I only found the answer by Googling and am still lost.

What's happening here? What's the use of this struct?

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"]
}

}

2 Answers

Structs are a type of framework to build objects in Swift.

Think of a struct, and classes for that matter, as a category. The Book struct defines a book as having an author, title, price, pubDate. This could be used in a book store's database, we can even add a var quantity to the struct so we can track how many are in the store.

For example, we have 2 books (I'll skip initialization):

let bookOne = Book()
let bookTwo = Book()

Now the store has sold 2 copies of bookOne and received 27 of bookTwo in a shipment. We could adjust the quantities based on these numbers:

bookOne.quantity -= 2   \\ 2 books sold
bookTwo.quantity += 27 \\ 27 copies received

They are both books, they have the same property categories (price, quantity, title, etc.), so rather than create the framework everytime you add a book, the Book struct allows you to build the framework once and use it across multiple versions of books. Hope this helps

Waylan Sands
PLUS
Waylan Sands
Courses Plus Student 5,824 Points

Thanks for the response. I appreciate you explaining the use of structs but what I'm looking for was a specific example of how to use this struct which was the answer to a lesson within the iOS course.

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"]

} }