如何找出用户表中是否有属性?

时间:2019-06-06 23:28:44

标签: swift firebase firebase-realtime-database

我有一个firebase表,我需要在其中查找表中是否存在特定用户的属性。表的结构如下:

Users
-Lf9xUh53VeL4OLlwqQo 
   username: "my@test.com"
   price:    "$100"
   special:  "No"

-L12345ff322223345fd 
   username: "my2@test.com"
   special:  "No"

我需要确定是否已为特定用户添加了“价格”。似乎无法弄清楚那个!

我很快需要类似的东西

        self.ref?.child("Users").queryOrdered(byChild: "username").queryEqual(toValue: username.text!).observe(.value, with: { (snapShot) in
        if (snapShot.value! is NSNull) {
            print("nothing found")
        } else {
            print("found it!")
            print(snapShot)

            let snapShotValue = snapShot.value as! [String:[String:Any]]
                Array(snapShotValue.values).forEach { // error here if it doesn't exist
                let price = $0["price"] as! String
                self.userPrice.text = price
            }}
        })

但是,如果价格不存在,则会出现错误。感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

使用as?代替as!

if let price = $0["price"] as? String {
  print(price)
}
else {
   print("No price")
}

或者不久之后

self.userPrice.text = ($0["price"] as? String) ?? "No price"