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

Jeff Norton
Jeff Norton
4,366 Points

I don't see how a dictionary that's passed into the initializer can contain both the title and the author.

If dict looks like var dict = ["J.R.R. Tolkien", "Lord of the Rings", "Lloyd Alexander", "The High King"] I don't see how I can pull out values from the dictionary in the initializer method, whether or not it was even a failable initializer. Can you help me see how to do that?

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

}

1 Answer

Jeff, your "dictionary" is an array, not a dictionary. See dict1 below.

struct Book {
    let title: String
    let author: String
    let price: String?
    let pubDate: String?

    init?(dict: [String: String]) {  //failable initializer
        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"]
    }
}

If you want to test this code in an Xcode playground add these lines after the above struct:

let dict1 = [ "title" : "Pride & Prejudice", "author" : "Jane Austen", "price" : "23.95"]
let b1 = Book(dict: dict1)
b1?.title
b1?.author
b1?.price
b1?.pubDate