billy_comic
billy_comic

Reputation: 899

Problem Accessing Items Within NSDictionary Swift

I'm a newb to Swift programming, but experience in other languages.

I am having problem accessing items within NSDictionary to build out view elements. This is coming back from a Firebase instance.

Can someone take a look at the code and the output and lead me in the right direction to access these object properties?

ref.observe(.value, with: { (snapshot) in
            for child in snapshot.children { //even though there is only 1 child
                let snap = child as! DataSnapshot
                let dict = snap.value as? NSDictionary
                for (joke, item) in dict ?? [:] {

                    print(joke)
                    print(item)



                }

            }
        })

This is the output from the print() methods.

joke2
{
    PostUser = "Bobby D";
    Punchline = "His money went to the movies.";
    Rating = 1;
    Setup = "Why did the dad go hungry?";
}
joke
{
    PostUser = "Billy G";
    Punchline = "Because he couldn't moo to a job.";
    Rating = 3;
    Setup = "Why did the cow go to school?";
}

Can someone tell me how to create items from these objects? Something like:

var posterName = joke.PostUser

When I try this, I get the error Value of type 'Any' has no member 'PostUser'. I've tried to access these DB object properties in multiple different ways described on SO and can't get any further.

Upvotes: 1

Views: 48

Answers (1)

P1xelfehler
P1xelfehler

Reputation: 1152

I would recommend you to convert the output into objects like this:

struct Item {
    var postUser: String?
    var punchline: String?
    var rating: Int?
    var setup: String?

    init(fromDict dict: [String: AnyObject] ) {
        self.postUser = dict["PostUser"] as? String
        self.punchline = dict["Punchline"] as? String
        self.rating = dict["Rating"] as? Int
        self.setup = dict["Setup"] as? String
    }
}

And use it like this:

ref.observe(.value, with: { (snapshot) in
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        guard let dict = snap.value as? [String: AnyObject] else { continue }
        let myItem = Item(fromDict: dict)
        print(myItem)
    }
})

But you could also access items in your dictionary directly like this:

let posterName = joke["PostUser"] as? String

Upvotes: 3

Related Questions