ios - 当我从字典接收 <null> 时如何正确解包和使用 nil - swift 3

标签 ios null swift3

我有一个结构:

    struct SomeTopic {

        var name: String?
        var parent: String?

        mutating func setName(name: String?) {
            self.name = name
        }

        mutating func setParent(parent: String?) {
            self.parent = parent
        }
    }

在其他类(class)中,我正在尝试访问字典 topicsList :

    class Blabla {

        var topics: Array<SomeTopic>!

        func topicsDidFinishLoading(topicsList: Array<Dictionary<String, Any>>) {

             if (self.topics != nil) {
                 self.topics.removeAll()
             }

             for topic in topicsList {

                 print(" Topic: ", topic)
                 var newTopic = SomeTopic()

                 newTopic.setName(name: topic["name"] as? String)
                 newTopic.setParent(parent: topic["parent"] as? String)

                 print("New topic created: ", newTopic)
                 self.topics.append(newTopic)
             }
        }

在函数“self.topics.append(newTopic)”的最后一行,我在运行时遇到错误: fatal error :在展开可选值时意外发现 nil。

打印语句:

主题:[“名称”:新闻,“父”:<null> ]

创建的新主题:SomeTopic(name: Optional("News"), parent: nil)

我试过使用:

    if let name = topic["name"] {

         newTopic.setName(topic["name"])
    } 

和 nil 测试的所有变体,但当 topic["name"] 的内容为 <null> 时它会进入 if-let 循环.

最佳答案

似乎问题只在声明中

    var topics: Array<SomeTopic>! 

代替

    var topics = Array<SomeTopic>()

这导致了崩溃,因为 self.topics 为零。

关于ios - 当我从字典接收 <null> 时如何正确解包和使用 nil - swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40469420/

相关文章:

swift - 我们如何设置添加 subview 的约束

ios - 互联网连接不良时viewWillAppear和viewDidAppear之间的延迟

ios - Objective C 中的数据类型和声明

ios - 将数组内的数组数组与另一个字符串数组数组进行比较

ios - Realm iOS : how expensive is it to initiate Realm with a bundled db?

c# - 总是添加一个空的事件处理程序可以吗?

jquery - Knockout.js 和 null

php - 如何在 PHP PDO 中插入空字符串而不是 null

ios - UISwipeGestureRecognizer 工作异常

ios - 如何在 UI 测试中关闭弹出框