我的具体任务是创建一个可失败的初始化程序,它接受字典作为参数并初始化结构的所有存储属性。键应该是“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": "$25"])
let book3 = Book(dict: ["title": "A book with no author"]) // nil
这表示一本书必须有一个作者
和一个标题
。如果两者都没有,它将失败。 price
和 pubDate
是可选的。
关于swift - 如何从 String 和 String 初始化字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366314/