Tarvo Mäesepp
Tarvo Mäesepp

Reputation: 4533

Retrieve children from Firebase into dictionary (Swift 3)

I am converting my fully working project (Swift 2) to Swift 3. I am stuck with a syntax change. This is the function that worked and now it doesn't like it and gives some weird suggestions which doesn't work.

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

I converted it and it has no errors, but it doesn't fill the productValues dictionary with values:

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

Can you help me to get this to fill my dictionary with values?

Upvotes: 0

Views: 733

Answers (1)

Callam
Callam

Reputation: 11539

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

Upvotes: 2

Related Questions