Eddy
Eddy

Reputation: 81

How to initialize a dictionary from String and String?

My specific task is to create a failable initializer that accepts a dictionary as the parameter and initializes all stored properties of the struct. The keys should be "title", "author", "price" and "pubDate".

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

I'm just not sure what to do here. I've gone down a few different routes and read the documentation on dictionaries and initializers without any luck. I'm mostly unsure how to set up the parameter for the init method. This is (abstract) idea I have

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

What am I missing?

Upvotes: 0

Views: 310

Answers (1)

Code Different
Code Different

Reputation: 93151

Try this:

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

    init?(dict: [String: String]) {
        guard dict["title"] != nil && dict["author"] != nil else {
            // A book must have title and author. If not, fail by returning nil
            return nil
        }

        self.title = dict["title"]!
        self.author = dict["author"]!
        self.price = dict["price"]
        self.pubDate = dict["pubDate"]
    }
}

// Usage:
let book1 = Book(dict: ["title": "Harry Potter", "author": "JK Rowling"])
let book2 = Book(dict: ["title": "Harry Potter", "author": "JK Rowling", "price": "$25"])
let book3 = Book(dict: ["title": "A book with no author"]) // nil

This says a book must have an author and a title. If it doesn't have either one, it will fail. price and pubDate are optional.

Upvotes: 2

Related Questions