将Firebase中的孩子检索到字典中(Swift 3)

时间:2016-10-02 17:44:29

标签: ios swift firebase firebase-realtime-database

我正在将完全正常工作的项目(Swift 2)转换为Swift 3.我对语法更改感到困惑。这是有效的功能,现在它不喜欢它,并提供了一些不起作用的奇怪建议。

var productsValue = [[String:AnyObject]]()
    let ref = FIRDatabase.database().reference().child("Snuses").queryOrderedByChild("Brand").queryEqualToValue(brandName)
            ref.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
                if snapshot.exists(){
                    if let products = snapshot.value?.allValues as? [[String:AnyObject]]{//This is most confusing part. It suggest me so weird things
                        self.productsValue = products
                        self.productstable.reloadData()
                    }
                }
            })

我转换它并且没有错误,但它没有用productValues字典填充值:

let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand").queryEqual(toValue: brandName)
        ref.observeSingleEvent(of: .value, with: { (snapshot) in
            if snapshot.exists(){
                if let products = (snapshot.value as AnyObject).allValues as? [[String:AnyObject]]{
                    self.productsValue = products
                    self.productsTable.reloadData()
                }
            }
        })

你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
    self.productsValue = snapshots.flatMap { $0.value as? [String:AnyObject] }
    self.productsTable.reloadData()
}