swift - 如何从 String 和 String 初始化字典?

标签 swift dictionary initialization

我的具体任务是创建一个可失败的初始化程序,它接受字典作为参数并初始化结构的所有存储属性。键应该是“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

这表示一本书必须有一个作者和一个标题。如果两者都没有,它将失败。 pricepubDate 是可选的。

关于swift - 如何从 String 和 String 初始化字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366314/

相关文章:

ios - 如果我多次初始化同一个属性会发生什么

java - 如何在java中将二维数组的所有元素初始化为任何特定值

c++ - (重新)将 vector 初始化为具有初始值的特定长度

python - 获取嵌套字典中所有键的列表

python - python字典中的匹配/计数列表

swift - 在类范围内声明和初始化静态对象

swift - 如何在 SwiftUI 中向 Viewmodifiers 添加闭包?

python - 在 python 中对 map 使用递归

ios - 如何在 Firebase 中创建新帐户而无需退出?在 iOS( swift )

swift - 点击搜索栏时,应用程序崩溃