无法将类型为NSTaggedPointerString的值转换为NSDictionary

时间:2016-11-07 07:00:02

标签: swift firebase

我正在尝试将Firebase值分配给我的结构:var productsArray = [Product]()但是我有一点错误:

  

无法转换类型' NSTaggedPointerString'至   '的NSDictionary'

我知道我不能直接分配它们,这就是我这样投射的原因:

self.snusProductTitle = (snapshot.value! as! NSDictionary)["Products"] as! String

转换:

func toAnyObject() -> [String: Any] {

        return ["Products": snusProductTitle as Any]
    }

像这样我追加:

let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand").queryEqual(toValue: brandName)
        ref.observeSingleEvent(of: .childAdded, with: { (posts) in
            self.productsArray.removeAll()
            var newPostsArray = [Product]()
            for post in posts.children {
                print(posts.value)//Look below image
                let newPost = Product(snapshot: post as! FIRDataSnapshot)
                newPostsArray.insert(newPost, at: 0)
            }

            self.productsArray = newPostsArray
            self.tableView.reloadData()

        }) { (error) in
            print(error.localizedDescription)
        }

这是最小的产品结构:

class Product: NSObject {
    var snusProductTitle: String!


    var ref: FIRDatabaseReference?

    init(snusProductTitle: String) {
        self.snusProductTitle = snusProductTitle
        self.ref = FIRDatabase.database().reference()
    }



    init(snapshot: FIRDataSnapshot){
        self.snusProductTitle = (snapshot.value! as! NSDictionary)["Products"] as! String
    }

    func toAnyObject() -> [String: Any] {
        return ["Products": snusProductTitle as Any]
    }
}

enter image description here

谷歌搜索时,我无法找到任何解决方案。

1 个答案:

答案 0 :(得分:1)

.childAdded一次只给FIRDataSnapshot ...所以不需要为此循环..你只需要传递你结构中的当前子项。

 self.productsArray.removeAll()
 var newPostsArray = [Product]()  

 let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand").queryEqual(toValue: brandName)
    ref.observe(FIRDataEventType.childAdded, with: { (posts) in

        let newPost = Product(snapshot: posts as! FIRDataSnapshot)
        newPostsArray.insert(newPost, at: 0)

        self.productsArray = newPostsArray
        self.tableView.reloadData()

    }) { (error) in
        print(error.localizedDescription)
    }