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

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