我的具体任务是创建一个可用的初始化程序,它接受字典作为参数并初始化结构的所有存储属性。键应该是"标题","作者","价格"和" pubDate"。
struct Book {
let title: String
let author: String
let price: String?
let pubDate: String?
我不知道该怎么做。我已经走了几条不同的路线,阅读了关于字典和初始化器的文档而没有任何运气。我大多不确定如何为init方法设置参数。这是(抽象)我的想法
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"]
}
我错过了什么?
答案 0 :(得分:2)
试试这个:
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
这说明一本书必须有author
和title
。如果它没有任何一个,它将失败。 price
和pubDate
是可选的。