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

How do I create the "dict" parameter?

How do I create the "dict" parameter? Note sure how to perform that part of the task?

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

    init?(title: String, author: String, price: String, pubDate: String) {
       self.title = title
        self.author = author
        self.price = price
        self.pubDate = pubDate
    }
}

2 Answers

well of course

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

// to create the instance we need to initialise it like below, 
//and since the dictionary has a key and value, we must return 2 strings like so below
    init?(dict: [String: String]){

      //so we just created the beginning of the init but didn't finish it, below is
     // the rest. You should get familiar with the Guard let and if let statements.
        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"]

    }
}

Thank you, I was confused. I usually have trouble with these challenges. However, when it's something I want to do, I usually have no problem figuring things out. Thank you for the help, I'm going to revisit those videos and try to reinforce my knowledge on this subject.

Hi Carl remember

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

// to create the instance we need to initialise it like below, 
//and since the dictionary has a key and value, we must return 2 strings like so below
    init?(dict: [String: String]){

I'm still confused. Xcode says I can only return "nil". So I do and it's still not working on the challenge? I still need help :/

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

    init?(dict: [String: String]){
        return nil
    }
}