Vodenjak
Vodenjak

Reputation: 813

How to properly unwrap and use nil when i'm receiving <null> from dictionary - swift 3

I have a struct:

    struct SomeTopic {

        var name: String?
        var parent: String?

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

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

In other class I am trying to access a dictionary 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)
             }
        }

In the last line of the function "self.topics.append(newTopic)" I am getting an error in runtime : fatal error: unexpectedly found nil while unwrapping an Optional value.

Print statements:

Topic: ["name": News, "parent": <null>]

New topic created: SomeTopic(name: Optional("News"), parent: nil)

I have tried using:

    if let name = topic["name"] {

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

and all the variations of testing for nil, but it passes into the if-let loop when the content of topic["name"] is <null>.

Upvotes: 1

Views: 291

Answers (1)

Vodenjak
Vodenjak

Reputation: 813

Seems like the problem was only in the declaring

    var topics: Array<SomeTopic>! 

instead of

    var topics = Array<SomeTopic>()

which caused the crash because self.topics were nil.

Upvotes: 1

Related Questions