在NSDictionary Swift

时间:2019-02-21 19:33:12

标签: swift firebase

我是Swift编程的新手,但是有其他语言的经验。

我在访问NSDictionary中的项目以构建视图元素时遇到问题。这是从Firebase实例回来的。

有人可以看看代码和输出,并引导我朝正确的方向访问这些对象属性吗?

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)



                }

            }
        })

这是print()方法的输出。

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?";
}

有人可以告诉我如何从这些对象创建商品吗?像这样:

var posterName = joke.PostUser

尝试此操作时,出现错误“ Any”类型的值没有成员“ PostUser”。我已尝试以SO上描述的多种不同方式访问这些数据库对象属性,并且无法获得进一步的信息。

1 个答案:

答案 0 :(得分:3)

我建议您将输出转换为如下对象:

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
    }
}

并像这样使用它:

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)
    }
})

但是您也可以像这样直接访问字典中的项目:

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