我无法获得snapshot.key swift ios

时间:2017-04-25 16:22:16

标签: ios swift string get snapshot

此代码获取值snap(电子邮件,名称)。我需要获取密钥(RxLV2i1)。如何改变代码?

FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
            if let dictionary = snapshot.value as? [String: AnyObject]{
                let user = Subject()
                user.setValuesForKeys(dictionary)
                self.subjects.append(user)
                DispatchQueue.main.async(execute: {
                    self.tableView.reloadData()
                })
            }    }, withCancel: nil)

例如:

Snap (RxLV2i1) {
     email = "Test1@gmail.com";
     name = "Test1 test1";
}

当我从snapshot.value更改为snapshot.key时 - 显示消息:

  

来自' String?!'到不相关的类型' [[String:AnyObject]]'总是   失败

1 个答案:

答案 0 :(得分:1)

如果您想获取快照键,只需执行

 let key = snapshot.key
 print(snapshot.key)

你的代码......

FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject]{
            let user = Subject()
            user.setValuesForKeys(dictionary)

  // Also if you add another variable called 'id' to your user object, you can set that as well to 'user.id = snapshot.key'
            let key = snapshot.key
            print(snapshot.key)

            self.subjects.append(user)
            DispatchQueue.main.async(execute: {
                self.tableView.reloadData()
            })
      }    }, withCancel: nil)