如何从 String 和 String 初始化字典?
How to initialize a dictionary from String and String?
我的具体任务是创建一个可失败的初始化程序,它接受字典作为参数并初始化结构的所有存储属性。键应该是 "title"、"author"、"price" 和 "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"]
}
我错过了什么?
试试这个:
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": ""])
let book3 = Book(dict: ["title": "A book with no author"]) // nil
这表示一本书必须有 author
和 title
。如果两者都没有,它将失败。 price
和 pubDate
是可选的。
我的具体任务是创建一个可失败的初始化程序,它接受字典作为参数并初始化结构的所有存储属性。键应该是 "title"、"author"、"price" 和 "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"]
}
我错过了什么?
试试这个:
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": ""])
let book3 = Book(dict: ["title": "A book with no author"]) // nil
这表示一本书必须有 author
和 title
。如果两者都没有,它将失败。 price
和 pubDate
是可选的。